开发者

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

开发者 https://www.devze.com 2023-01-03 20:18 出处:网络
I currently h开发者_运维知识库ave a view and I would like to change it into a UIImage. I would like to do this because the UIImage class is much better for what I need to do. How would you capture the

I currently h开发者_运维知识库ave a view and I would like to change it into a UIImage. I would like to do this because the UIImage class is much better for what I need to do. How would you capture the contents of a UIView and copy the contents into a 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:

#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. Hope that helps!


Add Following method to UIView category and use

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号