SmallChess
SmallChess

Reputation: 8146

How to select only a portion of UIView for converting to UIImage

I have the following for converting a UIView to UIImage

+(UIImage*) createUIImageFromView:(UIView *)view frame:(CGRect)frame;
{
    if (UIGraphicsBeginImageContextWithOptions != NULL)
    {
        UIGraphicsBeginImageContextWithOptions(frame.size, NO, 2.0f);
    }
    else
    {
        UIGraphicsBeginImageContext(view.frame.size);
    }

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

However, I can only select the size of the image but not where in the UIView should be converted to the image. For example, if I want to convert the rectangle CGRect(10,10,20,20) only but not the entire UIView, how do I do it?

Upvotes: 3

Views: 385

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185831

You can set the coordinate transformation matrix on your context. This allows you to change the coordinate system, so when the layer draws at (0,0), it will actually render somewhere else in the context. The functions you want to use to actually modify the CTM are documented in the Transforming User Space section of the CGContext docs.

Upvotes: 4

Related Questions