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

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

问题描述

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

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

当用户按下按钮时,我想让代码从任何地方创建图像UIScrollView的一部分位于我用CGRect指定的区域内。

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.

有什么想法吗?

干杯,
Andre

Cheers, Andre

推荐答案

我已经设法得到它。

这是我的解决方案,基于网上的一些不同的:

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

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

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