绘制不同的线条
-
画矩形
- (void)drawRect:(CGRect)rect { // 使用BezierPath进行绘制 UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(50, 50, 110, 120)]; [path stroke]; }
-
圆角矩形
- (void)drawRect:(CGRect)rect { // 使用BezierPath进行绘制 UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(50, 50, 110, 120)]; [path stroke]; }
-
椭圆的画法
// C语言的方式 - (void)drawRect:(CGRect)rect { // 获取上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 在rect区域内进行椭圆绘制 CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 150, 50)); // 绘制 CGContextStrokePath(ctx); } // OC方法 - (void)drawRect:(CGRect)rect { // 使用BezierPath进行绘制 UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 160, 60)]; [path stroke]; }
-
圆弧的画法
// c的方式 - (void)drawRect:(CGRect)rect { // 圆弧 CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextAddArc(ctx, 50, 50, 50, 0, M_PI * 2, YES); CGContextStrokePath(ctx); } // OC的方式 - (void)drawRect:(CGRect)rect { UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100) radius:50 startAngle:0 endAngle:M_PI clockwise:YES]; [path stroke]; }
-
五角星的画法
- (void)drawRect:(CGRect)rect { UIBezierPath* path = [UIBezierPath bezierPath]; NSMutableArray *arrs = [NSMutableArray array]; for (int i = 0; i< 5; i++) { CGFloat start = (3 * M_PI_2) + (i * M_PI * 2 / 5); CGFloat end = (start + M_PI * 2 / 5 * 2) + (i * M_PI * 2 / 5); [path addArcWithCenter:CGPointMake(150, 150) radius:100 startAngle:start endAngle:end clockwise:YES]; CGPoint point = [path currentPoint]; NSValue *value = [NSValue valueWithCGPoint:point]; [arrs addObject:value]; } UIBezierPath *p = [UIBezierPath bezierPath]; for (int i = 0; i< arrs.count; i++) { if (i == arrs.count - 1) { [[UIColor redColor]set]; CGPoint point = [arrs[i] CGPointValue]; [p moveToPoint:point]; [p addLineToPoint:[arrs[0] CGPointValue]]; [p stroke]; return; } CGPoint start = [arrs[i] CGPointValue]; [p moveToPoint:start]; CGPoint end = [arrs[i+1] CGPointValue]; [p addLineToPoint:end]; [p stroke]; } }