繪制不同的線條
-
畫矩形
- (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]; } }