需要将UIView捕获到UIImage中,包括所有子视图

时间:2010-06-27 23:48:45

标签: iphone uiview uiimage

我需要将UIView及其所有子视图捕获到UIImage中。问题是部分视图在屏幕外,所以我无法使用屏幕捕获功能,当我尝试使用UIGraphicsGetImageFromCurrentImageContext()函数时,它似乎也不会捕获子视图。它应该捕获子视图,我只是做错了吗?如果没有,还有其他方法可以实现吗?

4 个答案:

答案 0 :(得分:28)

这是正确的方法:

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]); 
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

此方法是UIImage类的扩展方法,它还可以在任何未来的高分辨率设备上使图像看起来很好。

答案 1 :(得分:2)

你的意思是

UIGraphicsBeginImageContext(view.bounds.size);
[view.layer drawInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

不起作用?我很确定它应该......

答案 2 :(得分:0)

这是一个Swift 2.x版本,如果你首先创建一个UIViews数组来展平,它应该可以工作:

// Flattens <allViews> into single UIImage
func flattenViews(allViews: [UIView]) -> UIImage? {
    // Return nil if <allViews> empty
    if (allViews.isEmpty) {
        return nil
    }

    // If here, compose image out of views in <allViews>
    // Create graphics context
    UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, UIScreen.mainScreen().scale)
    let context = UIGraphicsGetCurrentContext()
    CGContextSetInterpolationQuality(context, CGInterpolationQuality.High)

    // Draw each view into context
    for curView in allViews {
        curView.drawViewHierarchyInRect(curView.frame, afterScreenUpdates: false)
    }

    // Extract image & end context
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    // Return image
    return image
}

答案 3 :(得分:0)

Swift 4+版本:

func getImage(from view:UIView) -> UIImage? {

    defer { UIGraphicsEndImageContext() }
    UIGraphicsBeginImageContextWithOptions(view.frame.size, true, UIScreen.main.scale)
    guard let context =  UIGraphicsGetCurrentContext() else { return nil }
    view.layer.render(in: context)
    return UIGraphicsGetImageFromCurrentImageContext()   

}