- (void)drawRect:(CGRect)rect { // 拿到当前的图形上下文 CGContextRef ref = UIGraphicsGetCurrentContext(); // 拼接路径并且放到图形上下文 CGContextMoveToPoint(ref, 100, 100); CGContextAddLineToPoint(ref, 150, 150); CGContextStrokePath(ref); }
// OC方法,贝塞尔曲线 UIBezierPath *path = [UIBezierPath bezierPath]; [path moveToPoint:CGPointMake(10, 10)]; [path addLineToPoint:CGPointMake(100, 100)]; [path stroke];
- (void)test4 { // 画弧 // UIBezierPath* path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(150, 150) radius:100 startAngle:0 endAngle:M_PI_4 clockwise:YES]; // // [path stroke]; CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextAddArc(ctx, 150, 150, 100, 0, M_PI_4, 1); CGContextStrokePath(ctx); }
- (void)test3 { // 椭圆 // [[UIBezierPath bezierPathWithOvalInRect:CGRectMake(100, 100, 200, 100)] stroke]; CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextAddEllipseInRect(ctx, CGRectMake(100, 100, 100, 200)); CGContextStrokePath(ctx); }
- (void)test2 { // 圆角矩形 [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(100, 100, 100, 100) cornerRadius:50] stroke]; }
- (void)test1 { // 矩形 UIBezierPath* path = [UIBezierPath bezierPathWithRect:CGRectMake(100, 100, 100, 100)]; [path stroke]; }
// 饼状图 - (void)drawRect:(CGRect)rect { // 模拟服务器传过来要绘制的一组数据 NSArray *array = @[@0.1,@0.3,@0.2,@0.4]; CGFloat start = 0; CGFloat end = 0; for (int i = 0; i< array.count; i++) { end = 2 * M_PI * [array[i] floatValue] + end; // 画弧 UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(150, 150) radius:80 startAngle:start endAngle:end clockwise:true]; // 弧链接圆心变成披萨 [path addLineToPoint:CGPointMake(150, 150)]; // 随机颜色 [[self randomColor] setFill]; // 填充 [path fill]; start = end; } } // 随机颜色 - (UIColor *)randomColor { CGFloat randR = arc4random() % 255/256.0; CGFloat randG = arc4random() % 255/256.0; CGFloat randB = arc4random() % 255/256.0; return [UIColor colorWithRed:randR green:randG blue:randB alpha:1.0]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self setNeedsDisplay]; }
原文:http://www.cnblogs.com/aixiaoxin/p/4963602.html