gpt4 book ai didi

ios - snapshotViewAfterScreenUpdates 创建空白图像

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:55:44 25 4
gpt4 key购买 nike

我正在尝试使用以下代码创建一些复合 UIImage 对象:

someImageView.image = [ImageMaker coolImage];

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;
}

我刚得到一张空白的黑色图像。我该如何解决?

最佳答案

-snapshotViewAfterScreenUpdates: 提供 YES 意味着它需要回到运行循环才能实际绘制图像。如果您提供 NO,它会立即尝试,但如果您的 View 不在屏幕上或尚未绘制到屏幕上,则快照将为空。

要可靠地获取图像:

- (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];
}];

关于ios - snapshotViewAfterScreenUpdates 创建空白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27913285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com