Wednesday, March 26, 2014

iOS working with Layers

What is a CALayer?

CALayer manages image based content and allows a developer to perform animations on that content. Layers are often backing store for views but also can be used without views to  display content. Layers main job is to draw the contents that we provide but layer itself is having some attributes that can be set such as background color, corner radius etc. Layer itself contain information about the geometry of its contents. This helps to provide transformation,

A Layer can be created by a UIView object or can be explicitly created using [CALayer layer] method. If former, the UIView itself is the delegate and we should not change this relationship. But if it is explicitly created, then we can set a delegate object.

To access the CALayer from a view, the below method can be used

 CALayer *mylayer = myview.layer;

The above is mainly used to draw shadow around an imageview or something like this.

If using CALayer by its own, i.e. do not take from a UIView, we can use any of the subclasses such as CAGradientLayer, CATextLayer, CAShapeLayer, etc.

The below code sets the background frame and the color and the corner radius

self.view.layer.backgroundColor = [UIColor orangeColor].CGColor;
self.view.layer.cornerRadius = 20.0;
self.view.layer.frame = CGRectInset(self.view.layer.frame, 20, 20);

It is also possible to create sub layers for layers. The code is as below for this

CALayer *sublayer = [CALayer layer];
sublayer.backgroundColor = [UIColor blueColor].CGColor;
sublayer.shadowOffset = CGSizeMake(0,3);
sublayer.shadowRadius = 0.3;
sublayer.shadowColor = [UIColor blackColor].CGColor;
sublayer.shadowOpacity = 0.8;
sublayer.frame = CGRectMake(30,30,128,128);

[self.view.layer addSubLayer:sublayer];

It is also possible to give an image to a sublayer. The code is like below. 
sublayer.contents = [UIImage imagenamed:@"myimage.png"].CGImage;
sublayer.borderColor = [UIColor blackColor].CGColor;
sublayer.borderWidth = 2.0

There is also ways to draw custom content inside a CALayer instead of giving the image content to it. the concept is much simiar to drawing in view. We need to declare a delegate and implement the drawLayer:InContext method.  





No comments:

Post a Comment