sol*_*eil 2 uiview uiimageview uiimage ios
我正在尝试使用以下代码创建一些复合UIImage对象:
someImageView.image = [ImageMaker coolImage];
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我刚刚拿回一张空白的黑色图片.我该怎么办?
供应YES用于-snapshotViewAfterScreenUpdates:意味着它需要回一趟到runloop实际绘制图像.如果您提供NO,它将立即尝试,但如果您的视图在屏幕外或尚未绘制到屏幕上,则快照将为空.
要可靠地获取图像:
- (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]);
}
});
}
Run Code Online (Sandbox Code Playgroud)
你会像这样使用它:
[someObject withCoolImage:^(UIImage *image){
[self doSomethingWithImage:image];
}];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8500 次 |
| 最近记录: |