Get UIImage from view's layers?

2020-02-11 02:15发布

问题:

I have a view which has sublayers whose contents are images.

I was hoping to get the view's image by myView.image but apparently the view doesn't have image just layers.

How do I create a UIImage from view's layers?

回答1:

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

Note: you need to include QuartzCore for this.



回答2:

CGRect myRect =CGRectMake(0, 0, 300, 300);// [self.view bounds];
UIGraphicsBeginImageContext(myRect.size);

CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, myRect);

[self.view.layer renderInContext:ctx];
UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();