achiral
achiral

Reputation: 601

iOS - Saving only a part of a UIView to PNG

I am using the following code to convert the contents of a UIView to a PNG image:

UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

This works fine. If the UIView is 500 pixels high, and I'd like to generate two images (one of the top half and one of the bottom half), how would I go about doing this?

Any help would be greatly appreciated.

Upvotes: 0

Views: 204

Answers (1)

rob mayoff
rob mayoff

Reputation: 386038

There are a few ways you could do this. One way is to draw it into one big image, then make two sub-images:

static UIImage *halfOfImage(UIImage *fullImage, CGFloat yOffset) {
    // Pass yOffset == 0 for the top half.
    // Pass yOffset == 0.5 for the bottom half.

    CGImageRef cgImage = fullImage.CGImage;
    size_t width = CGImageGetWidth(cgImage);
    size_t height = CGImageGetHeight(cgImage);
    CGRect rect = CGRectMake(0, height * yOffset, width, height * 0.5f);

    CGImageRef cgSubImage = CGImageCreateWithImageInRect(cgImage, rect);
    UIImage *subImage = [UIImage imageWithCGImage:cgSubImage scale:fullImage.scale
        orientation:fullImage.imageOrientation];
    CGImageRelease(cgSubImage);
    return subImage;
}

...
    UIGraphicsBeginImageContext(myView.bounds.size);
    [myView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImage *topHalfImage = halfOfImage(viewImage, 0);
    UIImage *bottomHalfImage = halfOfImage(viewImage, 0.5f);

Upvotes: 1

Related Questions