iOS 小知识-使用paintCode的需要注意的点

时间:2021-08-06 02:23:19

使用paintCode生成代码获取贝塞尔曲线,可以说是绘制图片和动画的利器.paintCode的使用可以参考这篇文http://www.jianshu.com/p/5e75408812df
我在使用paintCode的过程中遇到一些小坑,这里总结下.

1.图片选择标准.

并不是所有的图片都可以绘制.图片的选择要考虑用代码绘制的成本.如果色块和线条过多,耗费的人力和时间成本太高,可能就没有必要了.实际工作中会让UI提供svg格式的图片,然后拖到paintCode中生成代码.如果图片过于负责,人物肖像,头发,皮肤什么的,直接放一张图片也是可以的.最后就是生成图片非常依赖贝塞尔曲线,以这个标准很容易衡量是否适合绘制.

2.自动生成代码的使用

  • 绘制的上下文
    UIGraphicsGetCurrentContext();这个方法在drewRect等方法中直接使用没有问题,但是直接调用创建图片的时候会出现问题,解决方法是自己创建一个上下文.
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(bounds.size.width, bounds.size.height),
    false, [UIScreen mainScreen].scale);

  • 绘制速度.
    低端机型如4s会出现有的图片绘制速度很慢,影响用户体验,因此可以放入后台或异步线程绘制.

  • 图片缓存.
    一般来说,绘制是比较耗时的,绘制完成图片会保存到本地,下次使用的时候先判断有无该图片,没有才进行绘制.

3.示例代码如下

//从文件中读取图片
CGRect bounds = CGRectMake(0, 0, 640, 720);
NSString *path = [self imagePathWithImageName:@"图片名称"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
if (image) {
return image;
}
//如果文件不存在,则开始绘制.首先创建一个context UIGraphicsBeginImageContextWithOptions(CGSizeMake(bounds.size.width, bounds.size.height), false, [UIScreen mainScreen].scale);
//获取从paitCode自动生成的代码
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat scale = [self scale];
CGContextScaleCTM(context, scale, scale);
CGContextSetAllowsAntialiasing(context, true);
CGContextSetShouldAntialias(context, true);

UIColor* color3 = [UIColor colorWithRed: 0.936 green: 0.936 blue: 0.936 alpha: 0.5];

CGContextSaveGState(context);
CGContextBeginTransparencyLayer(context, NULL);

//以下代码是paintCode自动生成的
UIBezierPath* bezierPath = UIBezierPath.bezierPath;
[bezierPath moveToPoint: CGPointMake(0.07, 0)];
...
bezierPath.usesEvenOddFillRule = YES;

[color3 setFill];
[bezierPath fill];


CGContextEndTransparencyLayer(context);
CGContextRestoreGState(context);

CGContextAddPath(context, bezierPath.CGPath);
//最后,将图片保存到本地
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];

return image;