Search code examples
iosdrawingcore-graphicsquartz-2d

Getting image using UIGraphicsGetImageFromCurrentImageContext


I am trying to understand, UIgraphicsGetImageContext() function, from my understanding, its a function, which gets the image from current bitmap context, so whenver I draw something on my canvas, and call this function, I get the image drawn, but suppose I dont draw anything then also it extracts an empty image. So I want to understand, how can we check when the canvas(CGContext) is nil.

Below is my code which I tried, but its not working

 UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO,0.0);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    if(UIGraphicsGetCurrentContext() == nil)
    {
        NSLog(@"NIL");
    }
    else
    {   
        m_curImage = UIGraphicsGetImageFromCurrentImageContext();  
        UIGraphicsEndImageContext();
        NSLog(@"%@",m_curImage);       
    }

So friends, please let me know how to get this it will be helpful to me

Regards Ranjit


Solution

  • UIGraphicsGetCurrentContext() will only return nil if the stack of graphics contexts is empty. In your drawing code you will always have a drawing context so it won't return nil here. UIGraphicsBeginImageContextWithOptions pushes a new context on the stack.

    You cannot use UIGraphicsGetCurrentContext() to detect if you have drawn something in the context.