Friday, 10 June 2016

Add a overlay layer on UIView

 Sometime we want to add an overlay layer on the  UIView. We can add an overlay shaded layer using CALayer. As we know each UIView is backed by  a layer. We can add many different layer  as sublayer to UIView. By using CALayer  we add as many effects to UIView as we want . 

For example , to add a sublayer to the part of the UIView, we can write a method for it .   

-(void)addLayerOnView:(UIView *)view withPercentage:(CGFloat)percentage{
    
    CALayer * subLayer  = [[CAShapeLayer alloc]init];
    
    CGFloat requiredW = (percentage/100) * view.frame.size.width ;
    
    CGRect tmpFrame =  view.frame;
    tmpFrame.size.width = requiredW;
    subLayer.frame = tmpFrame;
    subLayer.position  = CGPointMake(subLayer.frame.size.width/2, subLayer.frame.size.height/2);
    subLayer.opacity = 0.5f;
    
    subLayer.backgroundColor =  [UIColor grayColor].CGColor;
    
    [view.layer addSublayer:subLayer];
}

The above defined method take a UIView and percentage  as arguments . UIView is an object on which we want to add a sublayer and percentage tell us to the area of UIView on which we want to add a transparent layer .

In method , We create an instance of CAShapeLayer . Then we get the required width of the layer. We want the width of the layer should be percentage of the total width of the UIView . So we get the Width using formula:

    CGFloat requiredW = (percentage/100) * view.frame.size.width ;

Then set the frame, position and background color of the layer.

subLayer.frame = tmpFrame;
    subLayer.position  = CGPointMake(subLayer.frame.size.width/2, subLayer.frame.size.height/2);

We want to layer should be little transparent , so we also set the opacity of the layer :

    subLayer.opacity = 0.5f;

Finally we set the layer as sublayer of the UIView .

    [view.layer addSublayer:subLayer];






No comments:

Post a Comment