开发者

How to create an image from a UIView / UIScrollView

开发者 https://www.devze.com 2022-12-24 14:44 出处:网络
I have an image in an UIScrollView, that can be scrolled and zoomed. When the user presses a but开发者_运维技巧ton, I want the code to create an image from whatever part of the UIScrollView is inside

I have an image in an UIScrollView, that can be scrolled and zoomed.

When the user presses a but开发者_运维技巧ton, I want the code to create an image from whatever part of the UIScrollView is inside an area I specify with a CGRect.

I've seen code to crop UIImages, but I can't adapt it to do the same for a view, because it uses CGContextDrawImage.

Any thoughts?

Cheers, Andre


I've managed to get it.

Here's my solution, based on a few different ones from the web:

- (UIImage *)imageByCropping:(UIScrollView *)imageToCrop toRect:(CGRect)rect
{
    CGSize pageSize = rect.size;
    UIGraphicsBeginImageContext(pageSize);

    CGContextRef resizedContext = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(resizedContext, -imageToCrop.contentOffset.x, -imageToCrop.contentOffset.y);
    [imageToCrop.layer renderInContext:resizedContext];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

which you call by using:

CGRect clippedRect = CGRectMake(0, 0, 320, 300);
picture.image = [self imageByCropping:myScrollView toRect:clippedRect];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号