UIkit
// 绘制矩形
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(160, 10, 40, 40)];
[[UIColor blackColor] setStroke];
[path stroke];
// 绘制圆形
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(60, 150) radius:40 startAngle:0 endAngle:M_PI * 2 clockwise:NO];
[[UIColor blackColor] setFill];
[path fill]
// 绘制三角形
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(130, 10)];
[path addLineToPoint:CGPointMake(110, 50)];
[path addLineToPoint:CGPointMake(150, 50)];
[path closePath];
[[UIColor blackColor] setStroke];
[path stroke];
// 绘制椭圆形
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(60, 10, 40, 40)];
[[UIColor blackColor] setStroke];
[path stroke];
// 绘制圆角矩形
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(100, 300, 40, 40) cornerRadius:10];
[[UIColor blackColor] setStroke];
[path stroke];
// 绘制弧线段
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(100, 400, 60, 30) byRoundingCorners:UIRectCornerTopLeft cornerRadii:CGSizeMake(5, 5)];
[[UIColor blackColor] setStroke];
[path stroke];
CoreGraphics
// 绘制矩形
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddRect(ctx, CGRectMake(200, 40, 40, 40));
CGContextSetStrokeColorWithColor(ctx, [UIColor blackColor].CGColor);
CGContextStrokePath(ctx);
// 绘制圆形
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddArc(ctx, 60, 60, 20, 0, M_PI/2, 0);
CGContextSetStrokeColorWithColor(ctx, [UIColor blackColor].CGColor);
CGContextStrokePath(ctx);
// 绘制三角形
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGPoint startPoint = CGPointMake(140, 40);
CGContextMoveToPoint(ctx, startPoint.x, startPoint.y);
CGContextAddLineToPoint(ctx, 120, 80);
CGContextAddLineToPoint(ctx, 160, 80);
CGContextClosePath(ctx);
CGContextSetStrokeColorWithColor(ctx, [UIColor blackColor].CGColor);
CGContextStrokePath(ctx);
// 绘制椭圆形
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, CGRectMake(280, 40, 50, 40));
CGContextSetStrokeColorWithColor(ctx, [UIColor blackColor].CGColor);
CGContextStrokePath(ctx);
坐标系
UIkit的坐标系是左上角为原点,CoreGraphics的坐标系与数学坐标系相同(原点在左下角),在- (void)draw方法进行绘制时,系统自动将坐标系转换成UIKit的坐标系。
- 坐标系的转换方法
// CoreGraphics坐标系转换成UIKit坐标系
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, 0, self.bounds.size.height);
CGContextScaleCTM(ctx, 1.0, - 1.0);