CAShapeLayer和UIBezierPath

一:贝塞尔曲线 UIBezierPath

使用UIBezierPath类可以创建基于矢量的路径,这个类再UIKit中。此类是Core Graphics框架关于path的一个封装。使用此类可以定义简单的形状,如椭圆或者矩形,或者有多个直线和曲线段组成的形状。

1、UIBezierPath基础

UIBezierPath对象是CGPathRef数据类型的封装。path如果是基于矢量形状的,都是直线和曲线段去创建。我们使用只线段去创建矩形和多边形,使用曲线段去创建弧(arc),圆或者其他复杂的曲线形状。每一段都包括一个或者多个点,绘图命令定义如何诠释这些点。每一个直线段或者曲线段的结束的地方是下一个的开始的地方。每一个连接的直线或者曲线段的集合成为subPath。一个UIBezierPath对象定义一个完整的路径包括一个或者多个subpaths。

创建和使用一个path对象的过程是分开的。创建path是第一步,包含以下步骤:

  • (1)、创建一个UIBezierPath对象;
  • (2)、使用方法moveToPoint:去设置初始线段的起点;
  • (3)、添加line或者curve去定义一个或者多个subpaths;
  • (4)、改变UIBezierPath对象跟绘图相关的属性。

例如:我们呢可以设置strokedPath的属性lineWidth和lineJoinStyle。也可以设置filledPath的属性usersEvenOddFullRule。
当创建path,我们应该管理path上面的点相对于原点(0,0),这样我们在随后就可以很容易的移动path了。为了绘制path对象,我们要用到stroke和fill方法。这些方法再current graphic context下渲染path的line和curve段。

2、使用UIBezierPath创建多边形—在path下面添加直线条形成多边形

多边形是一些简单的形状,这些形状是由一些直线线条组成,我们可以用
(1)、 - (void)moveToPoint:(CGPoint)point;
(2)、 - (void)addLineToPoint:(CGPoint)point;
方法去构建。

方法moveToPoint:设置我们想要创建形状的起点。从这点开始,我们可以用方法addLineToPoint:去创建一个形状的线段。
我们可以连续的创建line,每一个line的起点都是先前的终点,终点就是指定的点。
下面的代码描述了如何用线段去创建一个五边形。第五条线通过调用 - (void)closePath;方法得到的,它连接了最后一个点(0,40)和第一个点(100,0)

说明:closePath方法不仅结束一个shape的subpath表述,它也在最后一个点和第一个点之间画一条线段,如果我们画多边形的话,这个一个便利的方法我们不需要去画最后一条线。
例如:

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    UIColor *color = [UIColor redColor];
    [color set]; //设置线条颜色
    UIBezierPath* aPath = [UIBezierPath bezierPath];
    aPath.lineWidth = 5.0;
    aPath.lineCapStyle = kCGLineCapRound; //线条拐角
    aPath.lineJoinStyle = kCGLineCapRound; //终点处理
    // Set the starting point of the shape.
    [aPath moveToPoint:CGPointMake(100.0, 0.0)];
    // Draw the lines
    [aPath addLineToPoint:CGPointMake(200.0, 40.0)];
    [aPath addLineToPoint:CGPointMake(160, 140)];
    [aPath addLineToPoint:CGPointMake(40.0, 140)];
    [aPath addLineToPoint:CGPointMake(0.0, 40.0)];
    [aPath closePath];//第五条线通过调用closePath方法得到的
    [aPath stroke];//Draws line 根据坐标点连线
    //    [aPath fill];//填充
}

3、使用UIBezierPath创建矩形

使用如下方法即可:

+ (UIBezierPath *)bezierPathWithRect:(CGRect)rect;

例如:

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    UIColor *color = [UIColor redColor];
    [color set]; //设置线条颜色
    UIColor *fillColor = [UIColor yellowColor];
    [fillColor setFill];
    UIBezierPath* aPath = [UIBezierPath bezierPathWithRect:CGRectMake(20, 20, 100, 50)];
    aPath.lineWidth = 5.0;
    aPath.lineCapStyle = kCGLineCapRound; //线条拐角
    aPath.lineJoinStyle = kCGLineCapRound; //终点处理
    [aPath stroke];
}

4、使用UIBezierPath创建圆形或者椭圆形

使用这个方法即可:

+ (UIBezierPath *)bezierPathWithOvalInRect:(CGRect)rect;

理解:这个方法根据传入的rect矩形参数绘制一个内切曲线。当传入的rect是一个正方形时,绘制的图像是一个内切圆;当传入的rect是一个长方形时,绘制的图像是一个内切椭圆。

例如:

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    UIColor *color = [UIColor redColor];
    [color set]; //设置线条颜色
    UIColor *fillColor = [UIColor yellowColor];
    [fillColor setFill];
    UIBezierPath* aPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(20, 20, 100, 50)];
    aPath.lineWidth = 5.0;
    aPath.lineCapStyle = kCGLineCapRound; //线条拐角
    aPath.lineJoinStyle = kCGLineCapRound; //终点处理
    [aPath stroke];
}

5、使用UIBezierPath创建一段弧线

使用这个方法:

+ (UIBezierPath *)bezierPathWithArcCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:(BOOL)clockwise;

解释:其中的参数分别指定:这段圆弧的中心,半径,开始角度,结束角度,是否顺时针方向。

例如:

#define   pi 3.14159265359
#define   DEGREES_TO_RADIANS(degrees)  ((pi * degrees)/ 180)
- (void)drawRect:(CGRect)rect
{
    UIColor *color = [UIColor redColor];
    [color set]; //设置线条颜色
    UIBezierPath* aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(150, 150) radius:75 startAngle:0 endAngle:DEGREES_TO_RADIANS(135) clockwise:YES];
    aPath.lineWidth = 5.0;
    aPath.lineCapStyle = kCGLineCapRound; //线条拐角
    aPath.lineJoinStyle = kCGLineCapRound; //终点处理
    [aPath stroke];
}

6、UIBezierPath类提供了添加二次贝塞尔曲线和三次贝塞尔曲线的支持

曲线段在当前点开始,在指定的点结束。曲线的形状有开始点,结束点,一个或者多个控制点的切线定义。下图显示了两种曲线类型的相似,以及控制点和curve形状的关系。

(1)、绘制二次贝塞尔曲线

使用到这个方法:

- (void)addQuadCurveToPoint:(CGPoint)endPoint controlPoint:(CGPoint)controlPoint;
解释:其中的参数分别指定:结束点,控制点;

这里写图片描述
例如:

- (void)drawRect:(CGRect)rect
{
    UIColor *color = [UIColor redColor];
    [color set]; //设置线条颜色
    UIBezierPath* aPath = [UIBezierPath bezierPath];
    aPath.lineWidth = 5.0;
    aPath.lineCapStyle = kCGLineCapRound; //线条拐角
    aPath.lineJoinStyle = kCGLineCapRound; //终点处理
    [aPath moveToPoint:CGPointMake(20, 100)];
    [aPath addQuadCurveToPoint:CGPointMake(120, 100) controlPoint:CGPointMake(70, 0)];
    [aPath stroke];
}

(2)、绘制三次贝塞尔曲线

使用到这个方法:

- (void)addCurveToPoint:(CGPoint)endPoint controlPoint1:(CGPoint)controlPoint1 controlPoint2:(CGPoint)controlPoint2;

解释:其中的参数分别指定:结束点,第一个控制点,第二个控制点;

这里写图片描述
例如:

- (void)drawRect:(CGRect)rect
{
    UIColor *color = [UIColor redColor];
    [color set]; //设置线条颜色
    UIBezierPath* aPath = [UIBezierPath bezierPath];
    aPath.lineWidth = 5.0;
    aPath.lineCapStyle = kCGLineCapRound; //线条拐角
    aPath.lineJoinStyle = kCGLineCapRound; //终点处理
    [aPath moveToPoint:CGPointMake(20, 50)];
    [aPath addCurveToPoint:CGPointMake(220, 250) controlPoint1:CGPointMake(220, 50) controlPoint2:CGPointMake(20, 250)];
    [aPath stroke];
}

7、使用Core Graphics函数去修改path。

UIBezierPath类只是 CGPathRef数据类型和path绘图属性的一个封装。虽然通常我们可以用UIBezierPath类的方法去添加直线段和曲线 段,UIBezierPath类还提供了一个属性CGPath,我们可以用来直接修改底层的path data type。如果我们希望用Core Graphics 框架函数去创建path,则我们要用到此属性。
有两种方法可以用来修改和 UIBezierPath对象相关的path。可以完全的使用Core Graphics函数去修改path,也可以使用Core Graphics函数和UIBezierPath函数混合去修改。第一种方法在某些方面相对来说比较容易。我们可以创建一个CGPathRef数据类型, 并调用我们需要修改path信息的函数。
下面的代码就是赋值一个新的CGPathRef给UIBezierPath对象。
例如:

- (void)drawRect:(CGRect)rect
{
    UIColor *color = [UIColor redColor];
    [color set]; //设置线条颜色
    // Create the path data
    CGMutablePathRef cgPath = CGPathCreateMutable();
    CGPathAddEllipseInRect(cgPath, NULL, CGRectMake(0, 20, 300, 300));
    CGPathAddEllipseInRect(cgPath, NULL, CGRectMake(50, 70, 200, 200));
    // Now create the UIBezierPath object
    UIBezierPath* aPath = [UIBezierPath bezierPath];
    aPath.CGPath = cgPath;
    aPath.usesEvenOddFillRule = YES;
    [aPath stroke];
    // After assigning it to the UIBezierPath object, you can release
    // your CGPathRef data type safely.
    CGPathRelease(cgPath);
}

如果我们使用Core Graphics函数和UIBezierPath函数混合方法,我们必须小心的移动path 信息在两者之间。因为UIBezierPath类拥有自己底层的CGPathRef data type,我们不能简单的检索该类型并直接的修改它。相反,我们应该生成一个副本,然后修改此副本,然后赋值此副本给CGPath属性,如下代码:
例如:

- (void)drawRect:(CGRect)rect
{
    UIColor *color = [UIColor redColor];
    [color set]; //设置线条颜色
    UIBezierPath*    aPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 300, 300)];
    // Get the CGPathRef and create a mutable version.
    CGPathRef cgPath = aPath.CGPath;
    CGMutablePathRef  mutablePath = CGPathCreateMutableCopy(cgPath);
    // Modify the path and assign it back to the UIBezierPath object
    CGPathAddEllipseInRect(mutablePath, NULL, CGRectMake(50, 50, 200, 200));
    aPath.CGPath = mutablePath;
    // Release both the mutable copy of the path.
    CGPathRelease(mutablePath);
    [aPath stroke];
}

8、rendering(渲染)Bezier Path对象的内容。

当创建一个UIBezierPath对象之后,我们可以使用它的stroke和fill方法在current graphics context中去渲染它。在调用这些方法之前,我们要进行一些其他的任务去确保正确的绘制path。
使用UIColor类的方法去stroke和fill想要的颜色。
设置形状在目标视图中的位置。如果我们 创建的path相对于原点(0,0),则我们可以给current drawing context应用一个适当的affie transform。例如,我想drawing一个形状起始点在(0,0),我可以调用函数CGContextTranslateCTM,并指定水平和垂 直方向的translation值为10。调整graphic context相对于调整path对象的points是首选的方法,因为我们可以很容易的保存和撤销先前的graphics state。
更新path对象的drawing 属性。当渲染path时,UIBezierPath实例的drawing属性会覆盖graphics context下的属性值。
下面的代码实现了在一个自定义view中实现drawRect:方法中去绘制一个椭圆。椭圆边框矩形的左上角位于视图坐标系统的点(50,50)处。
Drawing a path in a view
例如:

- (void)drawRect:(CGRect)rect
{
    // Create an oval shape to draw.
    UIBezierPath* aPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 200, 100)];
    // Set the render colors
    [[UIColor blackColor] setStroke];
    [[UIColor redColor] setFill];
    CGContextRef aRef = UIGraphicsGetCurrentContext();
    // If you have content to draw after the shape,
    // save the current state before changing the transform
    //CGContextSaveGState(aRef);
    // Adjust the view's origin temporarily. The oval is
    // now drawn relative to the new origin point.
    CGContextTranslateCTM(aRef, 50, 50);
    // Adjust the drawing options as needed.
    aPath.lineWidth = 5;
    // Fill the path before stroking it so that the fill
    // color does not obscure the stroked line.
    [aPath fill];
    [aPath stroke];
    // Restore the graphics state before drawing any other content.
    //CGContextRestoreGState(aRef);
}

二:CAShapeLayer

1、属性

(1)、 @property CGPathRef path;
理解:从贝塞尔曲线获取的形状;
(2)、 @property CGColorRef fillColor;
理解:闭环填充颜色;
(3)、 @property(copy) NSString *fillRule;
/* fillRule values. */
CA_EXTERN NSString *const kCAFillRuleNonZero
__OSX_AVAILABLE_STARTING (__MAC_10_6, __IPHONE_3_0);
CA_EXTERN NSString *const kCAFillRuleEvenOdd
__OSX_AVAILABLE_STARTING (__MAC_10_6, __IPHONE_3_0);
(4)、 @property CGColorRef strokeColor;
理解:边缘线的颜色;
(5)、 @property CGFloat strokeStart;
理解:控制开始的外观;
(6)、 @property CGFloat strokeEnd;
理解:控制结束的外观;
(7)、 @property CGFloat lineWidth;
理解:设置路径的宽度,默认为1;
(8)、 @property(copy) NSString *lineCap;
理解:边缘线的类型;
/* lineCap values. */
CA_EXTERN NSString *const kCALineCapButt
__OSX_AVAILABLE_STARTING (__MAC_10_6, __IPHONE_3_0);
CA_EXTERN NSString *const kCALineCapRound
__OSX_AVAILABLE_STARTING (__MAC_10_6, __IPHONE_3_0);
CA_EXTERN NSString *const kCALineCapSquare
__OSX_AVAILABLE_STARTING (__MAC_10_6, __IPHONE_3_0);
(9)、 @property(copy) NSString *lineJoin;
理解:连接方式类型
/* lineJoin values. */
CA_EXTERN NSString *const kCALineJoinMiter
__OSX_AVAILABLE_STARTING (__MAC_10_6, __IPHONE_3_0);
CA_EXTERN NSString *const kCALineJoinRound
__OSX_AVAILABLE_STARTING (__MAC_10_6, __IPHONE_3_0);
CA_EXTERN NSString *const kCALineJoinBevel
__OSX_AVAILABLE_STARTING (__MAC_10_6, __IPHONE_3_0);

2、步骤:

使用CAShapeLayer与UIBezierPath可以实现不在view的drawRect方法中就画出一些想要的图形

  • (1)、新建UIBezierPath对象bezierPath
  • (2)、新建CAShapeLayer对象caShapeLayer
  • (3)、将bezierPath的CGPath赋值给caShapeLayer的path,即caShapeLayer.path = bezierPath.CGPath
  • (4)、把caShapeLayer添加到某个显示该图形的layer中

三、CAShapeLayer+ CAGradientLayer自定义路径

使用: @property(strong) CALayer *mask;

例如:

#define degreesToRadians(x) (M_PI*(x)/180.0)
- (void)viewDidLoad {
    [super viewDidLoad];
    UIView* bgView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
    bgView.backgroundColor = [UIColor redColor];
    [self.view addSubview:bgView];
    //画出一个完成的进度的背景轨道
    //创建一个路径图层
    CAShapeLayer* trackLayer = [CAShapeLayer layer];
    trackLayer.frame = bgView.bounds;
    [bgView.layer addSublayer:trackLayer];
    trackLayer.fillColor = [[UIColor clearColor] CGColor];
    //指定path的渲染颜色
    trackLayer.strokeColor = [[UIColor redColor] CGColor];
    //背景同学你就甘心做背景吧,不要太明显了,透明度小一点
    trackLayer.opacity = 1;
    //指定线的边缘是圆的
    trackLayer.lineCap = kCALineCapRound;
    //线的宽度
    trackLayer.lineWidth = 4;
    //上面说明过了用来构建圆形
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100) radius:(200-4)/2 startAngle:degreesToRadians(-210) endAngle:degreesToRadians(30) clockwise:YES];
    //把path传递給layer,然后layer会处理相应的渲染,整个逻辑和CoreGraph是一致的。
    trackLayer.path =[path CGPath];
    //动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    animation.duration = 1;
    animation.fromValue = @(0.0);
    animation.toValue = @(1.0);
    [trackLayer addAnimation:animation forKey:@"strokeEnd"];
    //创建背景图层
    CAGradientLayer *gradientLayer =  [CAGradientLayer layer];
    [gradientLayer setColors:[NSArray arrayWithObjects:
                               (id)[[[UIColor blackColor] colorWithAlphaComponent:1] CGColor],
                               (id)[[[UIColor yellowColor] colorWithAlphaComponent:1] CGColor],
                               (id)[[[UIColor blueColor] colorWithAlphaComponent:1] CGColor],
                               (id)[[UIColor clearColor] CGColor],
                               nil]];
    gradientLayer.frame = bgView.bounds;
    [gradientLayer setLocations:[NSArray arrayWithObjects:
                                  [NSNumber numberWithFloat:0.0],
                                  [NSNumber numberWithFloat:0.3],
                                  [NSNumber numberWithFloat:0.8],
                                  [NSNumber numberWithFloat:1.0],
                                  nil]];

    [gradientLayer setStartPoint:CGPointMake(0, 0.5)];
    [gradientLayer setEndPoint:CGPointMake(1, 0.5)];
    [gradientLayer setMask:trackLayer]; //用progressLayer来截取渐变层
    [bgView.layer addSublayer:gradientLayer];
}

这里写图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaoxiaobukuang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值