-
第一种是创建一个UIView子类, 用UIBezierPath画圆。
创建和使用path对象步骤:
1、 重写View的drawRect
方法
2、 创建UIBezierPath
的对象
3、 使用方法moveToPoint:
设置初始点
4、 根据具体要求使用UIBezierPath
类方法绘图(比如要画线、矩形、圆、弧?等)
5、 设置UIBezierPath
对象相关属性 (比如lineWidth
、lineJoinStyle
、aPath.lineCapStyle
、color
)
6、 使用stroke 或者 fill方法结束绘图
- (void)drawRect:(CGRect)rect {
UIColor *color = [UIColor redColor];
[color set]; //设置线条颜色
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(10, 10)];
[path addLineToPoint:CGPointMake(200, 80)];
path.lineWidth = 5.0;
path.lineCapStyle = kCGLineCapRound; //线条拐角
path.lineJoinStyle = kCGLineJoinRound; //终点处理
[path stroke];
}
-
第二种是使用CAShaperLayer绘图。
-
CAShapeLayer
属于QuartzCore框架,继承自CALayer。CAShapeLayer
是在坐标系内绘制贝塞尔曲线的,通过绘制贝塞尔曲线,设置shape(形状)的path(路径),从而绘制各种各样的图形以及不规则图形。因此,使用CAShapeLayer
需要与UIBezierPath
一起使用。UIBezierPath
类允许你在自定义的 View 中绘制和渲染由直线和曲线组成的路径。你可以在初始化的时候直接为你的UIBezierPath
指定一个几何图形。
通俗点就是UIBezierPath
用来指定绘制图形路径,而CAShapeLayer
就是根据路径来绘图的。//创建出CAShapeLayer self.shapeLayer = [CAShapeLayer layer]; self.shapeLayer.frame = CGRectMake(0, 0, 200, 200);//设置shapeLayer的尺寸和位置 self.shapeLayer.position = self.view.center; self.shapeLayer.fillColor = [UIColor clearColor].CGColor;//填充颜色为ClearColor //设置线条的宽度和颜色 self.shapeLayer.lineWidth = 1.0f; self.shapeLayer.strokeColor = [UIColor redColor].CGColor; //创建出圆形贝塞尔曲线 UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 200, 200)]; //让贝塞尔曲线与CAShapeLayer产生联系 self.shapeLayer.path = circlePath.CGPath; //添加并显示 [self.view.layer addSublayer:self.shapeLayer];