xcode 如何从 UIView / UIScrollView 创建图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2500915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:13:36  来源:igfitidea点击:

How to create an image from a UIView / UIScrollView

iphonexcodeimageuiscrollviewcrop

提问by Andre

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

我在 UIScrollView 中有一个图像,可以滚动和缩放。

When the user presses a button, I want the code to create an image from whatever part of the UIScrollView is inside an area I specify with a CGRect.

当用户按下按钮时,我希望代码从 UIScrollView 的任何部分创建一个图像,该部分位于我用 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.

我已经看到裁剪 UIImages 的代码,但我无法对其进行修改以对视图执行相同的操作,因为它使用了 CGContextDrawImage。

Any thoughts?

有什么想法吗?

Cheers, Andre

干杯,安德烈

回答by 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];