我有一个UIView,它有几个UIImageViews作为子视图。这些子视图中的每一个都应用了不同的仿射变换。我想把我的UIView的屏幕截图,捕获它作为UIImage或其他图像表示。

我已经尝试过的方法,将图层渲染为CGContext:

[view.layer renderInContext:UIGraphicsGetCurrentContext()];

不会保留我的子视图的定位或其他仿射变换。

我真的很感激正确的方向。

有帮助吗?

解决方案

试试这个:

UIGraphicsBeginImageContext(self.view.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

其他提示

这是一个Swift 2.x版本:

// This 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
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top