Friday, 6 May 2016

Drawing On CALayer

Layers are often used to provide the backing store for views but can also be used without a view to display content. Layer is a partner of UIVIew. A UIView does not actually draw itself onto the screen; it draws itself into its layer, and it is the layer that is portrayed on the screen.

For drawing on CALayer first call UIGraphicsPushContext(CGContextRef context) inside drawInContext: method, than write drawing code and at the end use UIGraphicsPopContext();

UIGraphicsPushContext(CGContextRef context)  function save the previous graphics state and make the specified context the current context.
UIGraphicsPopContext() function to balance calls to the UIGraphicsPushContext function.  

First Create a subclass of CALayer.
 Add code inside newly created subclass.

-(void) drawInContext:(CGContextRef)ctx{
   
       UIGraphicsPushContext(ctx);
     
     // Drawing code
    UIBezierPath *rectanglePath = [UIBezierPath bezierPath];
    
    //set color for stroke
    [[UIColor blackColor] setStroke];
    
    //Set move point(origin/top left corner)
    [rectanglePath moveToPoint:CGPointMake(0, 0)];
    
    //set top right corner
    [rectanglePath addLineToPoint:CGPointMake(self.frame.size.width, 0)];
    
    //set bottom right corner
    [rectanglePath addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height)];
   
    //set bottom left point
    [rectanglePath addLineToPoint:CGPointMake(0,    self.frame.size.height)];
    [rectanglePath closePath];
    rectanglePath.lineWidth = 2;
    [rectanglePath stroke];
    [super drawInContext:ctx];
    UIGraphicsPopContext();
}

No comments:

Post a Comment