如何捕获UIView的内容并将其转换为UIImage?

5

我目前有一个视图,我想将其转换为UIImage。我想这样做是因为UIImage类更适合我需要做的事情。您如何捕获UIView的内容并将内容复制到UIImage中?

谢谢,

-David

3个回答

7

像这样:

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

您需要包含CoreGraphics框架,并导入CALayer.h:
#import <QuartzCore/CALayer.h>

我知道这已经过时了,但是为了在Retina显示屏上获得清晰的图片,请使用UIGraphicsBeginImageContextWithOptions(myView.bounds.size, myView.opaque, 0.0); - Reed

2

这里,试试这个

CGImageRef screen = UIGetScreenImage();
UIImage *screenImage = [UIImage imageWithCGImage:screen];

那将会捕获屏幕截图,在理论上捕获所有视图元素,并提供一个UIImage供您使用。希望这可以帮到您!

嘿,那很酷,但问题是它捕捉了整个主视图,例如我在主视图中有一个选项卡栏,但我不想要最终的UIImage中包含它... 有什么解决方法吗?提前致谢, -大卫 - bobbypage
你可以尝试将UIImage裁剪到所需的精确x,y坐标。如果这对你来说不是一个好选择,那么这种方法可能不起作用。 - Raphael Caixeta
你可以在捕捉图像时将元素设置为不可见吗? - KTOV

0
将以下方法添加到UIView类别中并使用。
- (UIImage*) capture {
    UIGraphicsBeginImageContext(self.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接