Friday, 11 March 2016

CAShapeLayer

CAShapeLayer is a specialized subclass of CALayer that draws itself using the shape you define via the path property. path is an instance of CGPath. We could leverage the convenient UIBezierPath APIs to create a path, and then retrieve the CGPath from it. Besides all the animatable properties inherited from CALayer, there are other animatable properties that let you control attributes such as fill color, stroke color, line thickness, etc.


Set rounded corner of a 'UIView' using "CAShapeLayer" 

//First create a instance of UIView
UIView *rectangleView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 300, 300)];

//set background color of UIView
rectangleView.backgroundColor = [UIColor redColor];

//Add subview to main view
[self.view addSubview:rectangleView];

//Create a instance of CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];

//set path for CAShapeLayer property's 'path'
UIBezierPath *shapePath =[UIBezierPath bezierPathWithRoundedRect:rectangleView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10, 10)];

//set CAShapeLayer Path
shapeLayer.path = shapePath.CGPath;

//Add CAShapeLayer to subview
rectangleView.layer.mask = shapeLayer;

By using CAShapelayer we can specify radius for particular corners.

//Set  radius of UIView for Top right and bottom left corners only
UIBezierPath *shapePath =[UIBezierPath bezierPathWithRoundedRect:rectangleView.bounds byRoundingCorners:(UIRectCornerTopRight | UIRectCornerBottomLeft) cornerRadii:CGSizeMake(10, 10)];
    shapeLayer.path = shapePath.CGPath;
    rectangleView.layer.mask = shapeLayer;

No comments:

Post a Comment