【iOS】Quartz2D基本图形
一、画线段
1 - (void)drawRect:(CGRect)rect 2 { 3 // Drawing code 4 // 1.获得图形上下文 5 CGContextRef ctx = UIGraphicsGetCurrentContext(); 6 7 // 2.拼接图形(路径) 8 // 设置线段宽度 9 CGContextSetLineWidth(ctx, 10); 10 11 // 设置线段头尾部的样式 12 CGContextSetLineCap(ctx, kCGLineCapRound); 13 14 // 设置线段转折点的样式 15 CGContextSetLineJoin(ctx, kCGLineJoinRound); 16 17 18 /** 第1根线段(红色) **/ 19 // 设置颜色 20 CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1); 21 // 设置一个起点 22 CGContextMoveToPoint(ctx, 10, 10); 23 // 添加一条线段到(100, 100) 24 CGContextAddLineToPoint(ctx, 100, 100); 25 26 // 3.渲染显示到view上面(渲染一次) 27 CGContextStrokePath(ctx); 28 29 //------------------------ 30 31 /** 第2根线段(蓝色) **/ 32 // 设置颜色 33 CGContextSetRGBStrokeColor(ctx, 0, 0, 1, 1); 34 // 设置一个起点 35 CGContextMoveToPoint(ctx, 200, 190); 36 // 添加一条线段到(150, 40) 37 CGContextAddLineToPoint(ctx, 150, 40); 38 CGContextAddLineToPoint(ctx, 120, 60); 39 40 41 // 3.渲染显示到view上面 42 CGContextStrokePath(ctx); 43 }
运行效果:
二、画四边形和三角形
画四边形和三角形,就是利用线段将其连接起来。代码如下:
/** * 画四边形 */ void draw4Rect() { // 1.获得上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 2.画矩形 CGContextAddRect(ctx, CGRectMake(10, 10, 150, 100)); // set : 同时设置为实心和空心颜色 // setStroke : 设置空心颜色 // setFill : 设置实心颜色 [[UIColor whiteColor] set]; // CGContextSetRGBFillColor(ctx, 0, 0, 1, 1); // 3.绘制图形 CGContextFillPath(ctx); } /** * 画三角形 */ void drawTriangle() { // 1.获得上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 2.画三角形 CGContextMoveToPoint(ctx, 0, 0); CGContextAddLineToPoint(ctx, 100, 100); CGContextAddLineToPoint(ctx, 150, 80); // 关闭路径(连接起点和最后一个点) CGContextClosePath(ctx); // CGContextSetRGBStrokeColor(ctx, 0, 1, 0, 1); // 3.绘制图形 CGContextStrokePath(ctx); }