简体   繁体   English

如何捕获UIView的内容并将其更改为UIImage?

[英]How to capture the contents of a UIView and change it into a UIImage?

I currently have a view and I would like to change it into a UIImage. 我目前有一个视图,我想将其更改为UIImage。 I would like to do this because the UIImage class is much better for what I need to do. 我想这样做是因为UIImage类对于我需要做的事情要好得多。 How would you capture the contents of a UIView and copy the contents into a UIImage? 你如何捕获UIView的内容并将内容复制到UIImage中?

Thanks, 谢谢,

-David -大卫

Like this: 像这样:

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

You will need to include the CoreGraphics framework, and import the CALayer.h: 您需要包含CoreGraphics框架,并导入CALayer.h:

#import <QuartzCore/CALayer.h>

Here, try this 在这里,试试这个

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

That will take a screenshot of the screen, so in theory capturing all of the view's elements and gives you a UIImage to work off of. 这将截取屏幕截图,因此理论上捕获所有视图的元素,并为您提供UIImage。 Hope that helps! 希望有所帮助!

Add Following method to UIView category and use 将以下方法添加到UIView类别并使用

- (UIImage*) capture {
    UIGraphicsBeginImageContext(self.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM