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();
新闻热点
疑难解答