Core Animation CAShapeLayer

CAShapeLayer

我们在上面曾经用过CGPath代替图片来绘制阴影,同样的我们可以使用CGPath来绘制各种我们想要的图形,用来代替图片使用。

CAShapeLayerCALayer的子类,在绘制的时候它使用的是矢量图形,而不是 Bitmap Image,因此效率非常高。在使用的时候 只要我们定义好颜色 线条的宽度,然后用CGPath来定义出形状,剩下的 CAShapeLayer会自动渲染。当然我们也可以使用 Core GraphicsCALayer中绘制我们想要的内容,但是有使用 CAShapeLayer有它的好处,

我们看个小栗子 怎么使用 CASapeLayer

UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(175, 100)];
[path addArcWithCenter:CGPointMake(150, 100) 
                radius:25 
            startAngle:0 
              endAngle:2*M_PI
             clockwise:YES];

[path moveToPoint:CGPointMake(150, 125)];
[path addLineToPoint:CGPointMake(150, 175)]; 
[path addLineToPoint:CGPointMake(125, 225)];
[path moveToPoint:CGPointMake(150, 175)]; 
[path addLineToPoint:CGPointMake(175, 225)];
[path moveToPoint:CGPointMake(100, 150)];
[path addLineToPoint:CGPointMake(200, 150)];

CAShapeLayer *shapeLayer = [CAShapeLayer layer]; 
shapeLayer.strokeColor =    [UIColor redColor].CGColor; 
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.lineWidth = 5;
shapeLayer.lineJoin = kCALineJoinRound; 
shapeLayer.lineCap = kCALineCapRound;   
shapeLayer.path = path.CGPath;
[self.containerView.layer addSublayer:shapeLayer];

image lineWidth 就是线的宽度

lineCap 线头的效果

lineJoin 不同的线相交的地方的效果

圆角

我们曾经使用过 CALayercornerRadius属性来绘制圆角矩形,我们使用 CAShaplayer也可以实现这个效果,但是CAShaplayer更好的地方在于它可以定义每个角实现不同的效果。

CGRect rect = CGRectMake(50, 50, 150, 150);
UIView *testView = [[UIView alloc] initWithFrame:rect];
testView.backgroundColor = [UIColor redColor];
[self.view addSubview:testView];

CGSize radii = CGSizeMake(20, 20);
UIRectCorner corners = UIRectCornerTopRight |
UIRectCornerBottomRight | UIRectCornerBottomLeft;
//create path
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:testView.bounds
                                            byRoundingCorners:corners 
                                                  cornerRadii:radii];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.strokeColor = [UIColor greenColor].CGColor;
shapeLayer.fillColor=[UIColor redColor].CGColor;
shapeLayer.lineWidth = 1;
shapeLayer.lineJoin = kCALineJoinRound;
shapeLayer.lineCap = kCALineCapRound;
shapeLayer.path = path.CGPath;
testView.layer.mask =shapeLayer;

image