Convert UIView Layer to UIImage

后端 未结 7 1406
深忆病人
深忆病人 2020-12-29 10:34

I\'m playing Video using AVPlayerLayer in a View. I need to convert View to Image, I tried

[myview.layer renderInContext:context];

but thi

7条回答
  •  生来不讨喜
    2020-12-29 11:14

    Try taking a screenshot and clipping. Otherwise you may have to render view and all its subviews recursively.

    -(UIImage *)videoScreenCap:(CGRect)cropRect{
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext(self.window.bounds.size);
        [self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        NSData * data = UIImagePNGRepresentation(image);
        [data writeToFile:@"foo.png" atomically:YES];
    CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
    UIImage * img = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef);
    return img;
    }
    

提交回复
热议问题