您的位置:首页 > 产品设计 > UI/UE

ios CAShapeLayer和UIBezierPath

2016-03-31 14:04 585 查看
CAShapeLayer继承CALayer,因此,可使用CALayer的所有属性,但是,CAShapelayer需要和贝塞尔曲线配合使用才有意义。

现在简单的画一个圆形

<span style="font-size:14px;">- (void)test
{
CAShapeLayer *layer = [CAShapeLayer layer];
// 指定frame,只是为了设置宽度和高度
layer.frame = CGRectMake(0, 0, 200, 200);
// 设置居中显示
layer.position = self.view.center;
// 设置填充颜色
layer.fillColor = [UIColor redColor].CGColor;
// 设置线宽
layer.lineWidth = 2.3;
// 设置线的颜色
layer.strokeColor = [UIColor redColor].CGColor;

// 使用UIBezierPath创建路径,并在layer上进行渲染
CGRect frame = CGRectMake(0, 0, 200, 200);
UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:frame];
// 设置CAShapeLayer与UIBezierPath关联
layer.path = circlePath.CGPath;
// 将CAShaperLayer放到某个层上显示
[self.view.layer addSublayer:layer];

}
</span>


上面的代码简单的绘制了一个圆形

现在简单的介绍一下UIBezierPath,UIBezierPath可以简单的创建矢量的路径,此类
Core Graphics
框架关于路径的封装,使用此类可以定义简单的形状,入椭圆,矩形等

我们一般使用UIBezierPath画图的步骤(一般在drawRect方法中绘图)

1> 创建UIBezierPath对象,

2> 使用moveToPoint:设置初始线段的起点

3> 添加线或者曲线去定义或者多个子路径

4> 改变UIBezierPath对象跟绘图相关的属性

<span style="font-size:14px;">- (void)drawRect:(CGRect)rect {

UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(20, 20)];
[path addLineToPoint:CGPointMake(self.frame.size.width - 40, 20)];
[path addLineToPoint:CGPointMake(self.frame.size.width / 2, self.frame.size.height - 20)];

// 最后的闭合线是可以通过调用closePath方法来自动生成的,也可以调用-addLineToPoint:方法来添加
//  [path addLineToPoint:CGPointMake(20, 20)];

[path closePath];
// 设置线宽
path.lineWidth = 1.5;
// 设置填充颜色
UIColor *fillColor = [UIColor yellowColor];
[fillColor set];
[path fill];

// 设置画笔颜色
UIColor *strokeColor = [UIColor blueColor];
[strokeColor set];

// 根据我们设置的各个点连线
[path stroke];
}
</span>



再次声明:一般CAShapeLayer和UIBezierPath配合使用,附上本人的一个关于仿AppStore里的下载样式的按钮

下载地址:https://github.com/likelin/LKProgressButton.git
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: