Quartz2D 与 UIBezierPath 类似,用于绘制图像。
基本方法
在 - (void)drawRect:(CGRect)rect 方法中进行绘制渲染。
// 获取上下文
CGContextRef contextRef = UIGraphicsGetCurrentContext();
// 线条宽度
CGContextSetLineWidth(contextRef, 5);
// 连接处圆角
CGContextSetLineJoin(contextRef, kCGLineJoinRound);
// 线条末端圆角
CGContextSetLineCap(contextRef, kCGLineCapRound);
// 画矩形
CGContextAddRect(contextRef, CGRectMake(50, 50, 100, 100));
// 画直线
CGContextMoveToPoint(contextRef, 100, 200);
CGContextAddLineToPoint(contextRef, 200, 200);
// 圆心x,y 半径radius 开始结束弧度 绘制方向:YES - 逆时针
CGContextAddArc(contextRef, 100, 200, 100, 0, M_PI_2, 0);
// 贝塞尔曲线 控制点1,控制点2,结束点
CGContextAddCurveToPoint(contextRef, 100, 400, 200, 300, 300, 400);
// 二次曲线 控制点,结束点
CGContextAddQuadCurveToPoint(contextRef, 300, 700, 50, 500);
// 闭合
CGContextClosePath(contextRef);
通过以上基本设定可绘制出想要的图像,在通过以下几种方法得到相应的效果。
画线条
// 线条颜色
[[UIColor redColor] set];
//渲染
CGContextStrokePath(contextRef);
![](https://i-blog.csdnimg.cn/blog_migrate/cf2ba24997aebd877fac54465b44bc8c.png)
填充
// 填充颜色
CGContextSetRGBFillColor(contextRef, 0.3, 0.7, 0.6, 1);
CGContextFillPath(contextRef);
![](https://i-blog.csdnimg.cn/blog_migrate/dedb45886c666a076abb302ede481c3f.png)
裁剪
// 裁剪
CGContextClip(contextRef);
UIImage * image = [UIImage imageNamed:@"11.jpg"];
[image drawInRect:rect];
![](https://i-blog.csdnimg.cn/blog_migrate/393775be1683dc0f1dc7da02f823d9c3.png)
对图片上下文操作
- (void)test
{
// 开启图片类型的图形上下文
UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 300), NO, 0);
// 获取当前上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 画线
CGContextMoveToPoint(ctx, 100, 100);
CGContextAddRect(ctx, CGRectMake(0, 0, 200, 200));
// 裁剪
CGContextClip(ctx);
[self.imageView.image drawAtPoint:CGPointZero];
// 文字水印
[@"这是水印" drawAtPoint:CGPointMake(100, 150) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
// 图片水印
UIImage * logo = [UIImage imageNamed:@"44"];
[logo drawAtPoint:CGPointMake(50, 150)];
// 得到新图片
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
// 关闭上下文
UIGraphicsEndImageContext();
// 保存相册
UIImageWriteToSavedPhotosAlbum(image, NULL, NULL, NULL);
self.imageView.image = image;
}
可通过裁剪、添加水印等获得新图片。
![](https://i-blog.csdnimg.cn/blog_migrate/121be0b744a2e090c51a3443932313dc.png)
总结
Quartz2D 的用法和 UIBezierPath 很像,可用于基本的线条处理及图片处理,同样也可以制作柱状图,饼状图等等。
可参考之前的文章 UIBezierPath 画折线图。