从CGBitmapContext创建CGImage并添加到UIImageView

时间:2013-09-10 22:16:34

标签: objective-c core-graphics cgimageref cgbitmapcontextcreate cgbitmapcontext

我正在尝试通过创建CGBitMapContext来创建UICollectionViewCell的快照。我不完全清楚如何做到这一点或如何使用相关的类,但经过一些研究,我编写了以下方法,从我的UICollectionViewCell子类中调用:

- (void)snapShotOfCell
{
    float scaleFactor = [[UIScreen mainScreen] scale];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, self.frame.size.width * scaleFactor, self.frame.size.height * scaleFactor, 8, self.frame.size.width * scaleFactor * 4, colorSpace, kCGImageAlphaPremultipliedFirst);

    CGImageRef image = CGBitmapContextCreateImage(context);
    UIImage *snapShot = [[UIImage alloc]initWithCGImage:image];

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.frame];
    imageView.image = snapShot;
    imageView.opaque = YES;
    [self addSubview:imageView];

     CGImageRelease(image);
     CGContextRelease(context);
     CGColorSpaceRelease(colorSpace);
}

结果是图像没有出现。在调试时,我可以确定我有一个有效的(非零)上下文,CGImage,UIImage和UIImageView,但屏幕上没有任何内容。有人能告诉我我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

您可以将其作为类别添加到UIView中,任何视图都可以访问它

- (UIImage*) snapshot
{
    UIGraphicsBeginImageContextWithOptions(self.frame.size, YES /*opaque*/, 0 /*auto scale*/);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

然后你只需要从你的单元格对象中做[self addSubview:[[UIImageView alloc] initWithImage:self.snapshot]]

[编辑]

需要异步呈现(完全可以理解),这可以使用调度队列来实现。我认为这样可行:

typedef void(^ImageOutBlock)(UIImage* image);

- (void) snapshotAsync:(ImageOutBlock)block
{
    CGFloat scale = [[UIScreen mainScreen] scale];
    CALayer* layer = self.layer;
    CGRect frame = self.frame;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^() {
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(NULL, frame.size.width * scaleFactor, frame.size.height * scaleFactor, 8, frame.size.width * scaleFactor * 4, colorSpace, kCGImageAlphaPremultipliedFirst);
        UIGraphicsBeginImageContextWithOptions(frame.size, YES /*opaque*/, scale);
        [layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);
        dispatch_async(dispatch_get_main_queue(), ^() {
            block(image);
        });
    });
}

[编辑]

- (void) execute
{
    __weak typeof(self) weakSelf = self;
    [self snapshotAsync:^(UIImage* image) { 
        [weakSelf addSubview:[[UIImageView alloc] initWithImage:image]] 
    }];
}