snapshotViewAfterScreenUpdates 创建一个空白图像 [英] snapshotViewAfterScreenUpdates creating a blank image
本文介绍了snapshotViewAfterScreenUpdates 创建一个空白图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码创建一些复合 UIImage 对象:
I'm trying to create some composite UIImage objects with this code:
someImageView.image = [ImageMaker coolImage];
ImageMaker:
ImageMaker:
- (UIImage*)coolImage {
UIView *composite = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"coolImage"]]; //This is a valid image - can be viewed when debugger stops here
[composite addSubview:imgView];
UIView *snapshotView = [composite snapshotViewAfterScreenUpdates:YES];
//at this point snapshotView is just a blank image
UIImage *img = [self imageFromView:snapshotView];
return img;
}
- (UIImage *)imageFromView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
我只得到一个空白的黑色图像.我该如何解决?
I just get back a blank black image. How can I fix?
推荐答案
Supplying YES
for -snapshotViewAfterScreenUpdates:
意味着它需要回到 runloop 来实际绘制图片.如果您提供 NO
,它将立即尝试,但如果您的视图不在屏幕上或尚未绘制到屏幕上,则快照将为空.
Supplying YES
for -snapshotViewAfterScreenUpdates:
means it needs a trip back to the runloop to actually draw the image. If you supply NO
, it will try immediately, but if your view is off screen or otherwise hasn't yet drawn to the screen, the snapshot will be empty.
为了可靠地获取图像:
- (void)withCoolImage:(void (^)(UIImage *))block {
UIView *composite = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"coolImage"]]; //This is a valid image - can be viewed when debugger stops here
[composite addSubview:imgView];
UIView *snapshotView = [composite snapshotViewAfterScreenUpdates:YES];
// give it a chance to update the screen…
dispatch_async(dispatch_get_main_queue(), ^
{
// … and now it'll be a valid snapshot in here
if(block)
{
block([self imageFromView:snapshotView]);
}
});
}
你会像这样使用它:
[someObject withCoolImage:^(UIImage *image){
[self doSomethingWithImage:image];
}];
这篇关于snapshotViewAfterScreenUpdates 创建一个空白图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文