Quartz2D绘图
Quartz 2D绘图只能在UIView中重写drawRect:方法中进行绘制,其他地方都无效,会报错。
绘制过程:
1. 获取上下文 CGContextRef context = UIGraphicsGetCurrentContext();
2. 添加图形 CGContextAddRect(context , CGRectMake(50, 50, 100, 100));
3. 绘制图形 CGContextDrawPath(context ,kCGPathEOFill);
4. 关闭上下文 CGContextClosePath(context);
Quartz 2D 坐标系变换
1. CGContextRotateCTM(CGContextRef c, CGFloat angle)方法可以相对原点旋转上下文坐标系
2. CGContextTranslateCTM(CGContextRef c, CGFloat tx, CGFloat ty)方法可以相对原点平移上下文坐标系
3. CGContextScaleCTM(CGContextRef c, CGFloat sx, CGFloat sy)方法可以缩放上下文坐标系
注意:
转换坐标系前,使用CGContextSaveGState(CGContextRef c)保存当前上下文状态
坐标系转换后,使用CGContextRestoreGState(CGContextRef c)可以恢复之前保存的上下文状态
Quartz基本绘图方法
CGContextBeginPath开始一个新路径
CGContextMoveToPoint设置路径的起点
CGContextClosePath关闭路径
CGContextAddPath添加路径
CGContextAddLineToPoint在指定点添加线
CGContextAddLines添加多条线
CGContextAddRect添加矩形
CGContextAddRects添加多个矩形
CGContextAddEllipseInRect在矩形区域中添加椭圆
CGContextAddArc添加圆弧
CGContextAddArcToPoint在指定点添加圆弧
CGContextAddCurveToPoint在指定点添加曲线
CGContextDrawPath绘制路径
CGContextFillPath实心路径
CGContextFillRect实心矩形
CGContextFillRects多个实心矩形
CGContextFillEllipseInRect在矩形区域中绘制实心椭圆
CGContextStrokePath空心路径
CGContextStrokeRect空心矩形
CGContextStrokeRectWithWidth使用宽度绘制空心矩形
CGContextStrokeEllipseInRect在矩形区域中绘制空心椭圆
CGContextSetLineWidth 设置线宽
CGContextSetBlendMode 设置混合模式
CGContextSetShouldAntialias 设置抗锯齿效果
CGContextSetLineCap 设置线条收尾点样式
CGContextSetLineJoin 设置线条连接点样式
CGContextSetLineDash 设置虚线
绘制image
1. 获取图像上下文 UIGraphicsBeginImageContext(....);
2. 画图 CGRect rect = CGRectMake(....);
3. 设置颜色 [[UIColor redColor] set];
4. 填充 UIRectFill(rect);
5. 获取图像 UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
6. 关闭上下文 UIGraphicsEndImageContext
绘制PDF
1. 创建PDF上下文 UIGraphicsBeginPDFContextToFile(path, CGRectZero,NULL); path为沙盒路径;参数2若设为CGRectZero则建立612*792大小的页面
2. 创建PDF内容,需要分页设置,方法 UIGraphicsBeginPDFPage 创建一页。
3. 关闭PDF上下文 UIGraphicsEndPDFContext();