Quartz 2D是Core Graphics中关键的一部分,它包含了各种函数、数据类型以及对象,可以在内存中直接绘制视图和图像。但是Quartz 2D仅限于二维绘图。
Core Graphics是一个C语言API,所以名称都是以CG开头的函数都是C函数。
在iOS上面的坐标系统和传统的笛卡儿坐标系统是上下相反的。下面左图是笛卡儿坐标系统;右图是iOS系统中的坐标系统,Quartz 2D绘图时也遵循这一坐标系统。
新建一个视图G2DView继承UIView。
#import "G2DView.h" @implementation G2DView - (void)drawRect:(CGRect)rect{ /* 画直线 */ // 获取图形环境 CGContextRef context = UIGraphicsGetCurrentContext(); // 设置起点坐标 CGContextMoveToPoint(context, 10, 20); // 设置终点坐标 CGContextAddLineToPoint(context, 300, 20); // 设置线条颜色 CGContextSetRGBStrokeColor(context, 0.5, 1.0, 0, 1.0); // 设置线条宽度 CGContextSetLineWidth(context, 5); // 渲染 CGContextStrokePath(context); /* 画矩形 */ // 设置矩形的起点和宽度和高度 CGRect theRect = CGRectMake(10, 40, 80, 50); // 增加一个矩形 CGContextAddRect(context, theRect); // 设置矩形的边线宽度 CGContextSetLineWidth(context, 1); // 设置边线颜色 CGContextSetRGBStrokeColor(context, 0.2, 0.7, 0.9, 1.0); // 设置矩形内部填充颜色 CGContextSetRGBFillColor(context, 0.5, 1.0, 0, 1.0); // 渲染 CGContextDrawPath(context, kCGPathFillStroke); /* 画椭圆 */ // 设置椭圆形的起点和宽度和高度 CGRect EllipseInRect = CGRectMake(100, 40, 80, 50); // 增加一个椭圆形 CGContextAddEllipseInRect(context, EllipseInRect); // 设置椭圆形的边线宽度 CGContextSetLineWidth(context, 2); // 设置边线颜色 CGContextSetRGBStrokeColor(context, 0.26, 0.35, 0.15, 1.0); // 设置椭圆形内部填充颜色 CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0); // 渲染 CGContextDrawPath(context, kCGPathFillStroke); /* 画圆形 */ // 增加一个椭圆形 CGContextAddArc(context, 220, 65, 20, 0, 360, 0); // 设置椭圆形的边线宽度 CGContextSetLineWidth(context, 2); // 设置边线颜色 CGContextSetRGBStrokeColor(context, 0.26, 0.35, 0.15, 1.0); // 设置椭圆形内部填充颜色 CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0); // 渲染 CGContextDrawPath(context, kCGPathFillStroke); }
在画圆中这个函数CGContextAddArc里面参数比较多。
以上是官方的解释。
在VC中使用这个view:#import "ViewController.h" #import "G2DView.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; G2DView *view = [[G2DView alloc] init]; view.frame = CGRectMake(0, 20, 320, 200); view.backgroundColor = [UIColor whiteColor]; [self.view addSubview:view]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end