UIBeaierPath 与 CAShapeLayer

时间:2023-03-09 16:07:10
UIBeaierPath  与 CAShapeLayer

CAShapeLayer是基于贝塞尔曲线而存在的, 如果没有贝塞尔曲线提供路径来画出图形, CAShapeLayer就没有存在的意义, CAShapeLayer可以使得不用在   drawRect:方法中实现画图.

另外, CAShapeLayer是属于CoreAnimation框架的, 是基于GPU的来进行渲染的,

         不比使用CoreGraphic框架, 是基于CPU来渲染的, 所以CAShapeLayer效率相对比较高一些

下面我简单的使用CAShapeLayer和贝塞尔曲线画了矩形和椭圆形,

// 矩形(正方形)
- (void)createRect
{
// 创建矩形贝塞尔曲线路径
UIBezierPath *rect = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 20, 30)]; // 创建CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
// 设置尺寸
shapeLayer.frame = CGRectMake(0, 0, 100, 200);
// 设置位置
shapeLayer.position = self.view.center;
// 填充颜色
shapeLayer.fillColor = [UIColor whiteColor].CGColor;
// 路径颜色(边框)
shapeLayer.strokeColor = [UIColor blackColor].CGColor; // 关联
shapeLayer.path = rect.CGPath; // 显示
[self.view.layer addSublayer:shapeLayer];
} // 椭圆(圆)
- (void)createOval
{
// 创建椭圆形贝塞尔曲线路径
UIBezierPath *oval = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 200, 200)]; // 创建CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
// 设置尺寸,
shapeLayer.frame = CGRectMake(0, 0, 200, 200);
// 设置位置(设置的是shapeLayer的中心点位置)
shapeLayer.position = self.view.center;
// 设置背景颜色
shapeLayer.backgroundColor = [UIColor greenColor].CGColor;
// 设置填充颜色(注意, 这里不是设置背景颜色)
shapeLayer.fillColor = [UIColor redColor].CGColor;
// 设置边框颜色(路径颜色)
shapeLayer.strokeColor = [UIColor blueColor].CGColor; // 关联ShapeLayer和贝塞尔曲线
shapeLayer.path = oval.CGPath; // 显示
[self.view.layer addSublayer:shapeLayer]; }