如何从 UIView/UIScrollView 创建图像 [英] How to create an image from a UIView / UIScrollView

查看:30
本文介绍了如何从 UIView/UIScrollView 创建图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UIScrollView 中有一张图片,可以滚动和缩放.

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

当用户按下按钮时,我希望代码从我用 CGRect 指定的区域内的 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.

我见过裁剪 UIImages 的代码,但我无法调整它来为视图做同样的事情,因为它使用 CGContextDrawImage.

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

有什么想法吗?

干杯,安德烈

推荐答案

我已经搞定了.

这是我的解决方案,基于网络上的几个不同的解决方案:

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;
}

您使用以下方式调用:

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

这篇关于如何从 UIView/UIScrollView 创建图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆