IOS-绘图-UIBezierPath

介绍

    UIBezierPath类在UIKit包中,此类是Core Graphics框架关于路径的封装。使用此类可以定义简单的形状,如椭圆、矩形或者有多个直线和曲线段组成的形状等。

画图步骤

  1. 创建一个UIBezierPath对象
  2. 调用moveToPoint设置初始线段的起点
  3. 添加线或者曲线去定义一个或者多个子路径
  4. 改变UIBezierPath对象跟绘图相关的属性。如,我们可以设置画笔的属性、填充样式等
UIBezierPath *bezierPath = [UIBezierPath bezierPath];
//设置起点
[bezierPath moveToPoint:CGPointMake(30.0, 20.0)];
//设置终点
[bezierPath addLineToPoint:CGPointMake( 100.0, 50)];
// 设置边框颜色
[self.cColor setStroke];
//设置宽度
bezierPath.lineWidth = 2.0;
//绘制边框
[bezierPath stroke];

简单图形创建方法介绍

//适合创建任何图形
UIBezierPath *bezierPath = [UIBezierPath bezierPath];

//直角矩形
UIBezierPath* bezierPath = [UIBezierPath bezierPathWithRect:CGRectMake(20, 60, 100, 50)];

//圆角矩形
UIBezierPath* bezierPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(20, 60, 100, 50) cornerRadius:6.0];

//内切圆
UIBezierPath* bezierPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(20, 120, 50, 50)];

//椭圆
UIBezierPath* bezierPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(20, 120, 100, 50)];

描边和填充

//创建path
UIBezierPath *path = [UIBezierPath bezierPath];
// 添加圆到path
[path addArcWithCenter:self.center radius:100.0 startAngle:0.0 endAngle:M_PI*2 clockwise:YES];
// 设置描边宽度(为了让描边看上去更清楚)
[path setLineWidth:5.0];
//设置颜色(颜色设置也可以放在最上面,只要在绘制前都可以)
[[UIColor blueColor] setStroke];
[[UIColor redColor] setFill];
// 描边和填充
[path stroke];
[path fill];

    UIBezierPath颜色的设置并没有包含在自己类中,而是通过UIColor直接设置的。

//设置边框颜色
[[UIColor blueColor] setStroke];
//设置填充颜色
[[UIColor redColor] setFill];
//设置边框和填充颜色
[[UIColor greenColor] set];

使用图形上下文绘制

    我们绘制图形的时候,一般都是在继承UIView的子类中,重写drawRect方法。另外一种方式是在图形上下文中绘制。

//开始图像绘图
UIGraphicsBeginImageContext(self.view.bounds.size);

UIBezierPath *bezierPath = [UIBezierPath bezierPath];
//设置起点
[bezierPath moveToPoint:CGPointMake(30.0, 20.0)];
//设置终点
[bezierPath addLineToPoint:CGPointMake( 100.0, 50)];
// 设置边框颜色
[[UIColor redColor] setStroke];
//设置宽度
bezierPath.lineWidth = 2.0f;
//绘制边框
[bezierPath stroke];

//从Context中获取图像,并显示在界面上
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgView];

参考

[iOS UIBezierPath类 介绍]

http://justsee.iteye.com/blog/1972853

[iOS 简单的使用UIBezierPath绘制]

http://my.oschina.net/lanrenbar/blog/389379

[UIBezierPath精讲]

http://www.jianshu.com/p/734b34e82135

[iOS: 使用CGContextRef,CGPath和UIBezierPath来绘画]

https://www.mgenware.com/blog/?p=493