一、对Quartz2D的介绍
Quartz 2D是一个二维图形绘制引擎,支持iOS环境和Mac OS X环境。我们可以使用Quartz 2D API来实现许多功能,如基本路径的绘制、透明度、描影、绘制阴影、透明层、颜色管理、反锯齿、PDF文档生成和PDF元数据访问。在需要的时候,Quartz 2D还可以借助图形硬件的功能。
Quartz 2D在图像中使用了绘画者模型(painter’s model)。在绘画者模型中,每个连续的绘制操作都是将一个绘制层(a layer of ‘paint’)放置于一个画布(‘canvas’),我们通常称这个画布为(Page)。 Page上的绘图可以通过额外的绘制操作来叠加更多的绘图。Page上的图形对象只能通过叠加更多的绘图来改变。这个模型允许我们使用小的图元来构建复杂的图形。
Page可以是一张纸(如果输出设备是打印机),也可以是虚拟的纸张(如果输出设备是PDF文件),还可以是bitmap图像。这根据实际使用的graphics context而定。
二、画一些基本图像
代码:
//
// ShapeView.m
//
//
// Created by QiZhang on 11/26/15.
//
//
#import "ShapeView.h"
@implementation ShapeView
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
[self mydraw];
}
// 四分之一圆
- (void)circle_4
{
// 获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 拼接路径
CGPoint center = CGPointMake(100, 100);
CGFloat radius = 100;
CGFloat startA = 0;
CGFloat endA = M_PI_2;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
[path addLineToPoint:center];
// 把路径添加到上下文
CGContextAddPath(ctx, path.CGPath);
// 渲染上下文
CGContextFillPath(ctx); // 充满
}
// 四分之一圆弧
- (void)drawArc
{
// 获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 拼接路径
CGPoint center = CGPointMake(100, 100);
CGFloat radius = 100;
CGFloat startA = 0;
CGFloat endA = M_PI_2;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
// 把路径添加到上下文
CGContextAddPath(ctx, path.CGPath);
// 渲染
CGContextStrokePath(ctx);
}
// 画矩形
- (void)drawRectangle
{
// 获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 拼接路径
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(10, 10, 150, 150)];
CGContextAddPath(ctx, path.CGPath);
CGContextStrokePath(ctx);
}
// 画三角形
- (void)drawTriangle
{
// 1.获得上下文路径
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2.拼接路径
UIBezierPath *path = [UIBezierPath bezierPath];
CGPoint startP = CGPointMake(10, 10);
[path moveToPoint:startP];
[path addLineToPoint:CGPointMake(200, 190)];
[path addLineToPoint:CGPointMake(10, 190)];
[path closePath]; // 从路径的终点连接到起点
// 3.把路径添加到上下文
CGContextAddPath(ctx, path.CGPath);
// [[UIColor blueColor] setFill];
// [[UIColor redColor] setStroke];
//
// CGContextSetLineWidth(ctx, 15);
//
// // 渲染上下文
// CGContextDrawPath(ctx, kCGPathFillStroke);
CGContextStrokePath(ctx);
//
}
- (void)mydraw
{
// 1.获得上下文路径
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2.拼接路径
UIBezierPath *path = [UIBezierPath bezierPath];
CGPoint startP = CGPointMake(10, 10);
[path moveToPoint:startP];
[path addLineToPoint:CGPointMake(200, 190)];
[path addLineToPoint:CGPointMake(10, 190)];
[path closePath]; // 从路径的终点连接到起点
// 3.把路径添加到上下文
CGContextAddPath(ctx, path.CGPath);
[[UIColor blueColor] setFill];
[[UIColor redColor] setStroke];
CGContextSetLineWidth(ctx, 15);
// 渲染上下文
CGContextDrawPath(ctx, kCGPathFillStroke);
}
@end
结果截图: