2009-09-15 33 views
6

我有一个UIView,有几个UIImageView作为子视图。这些子视图中的每一个都应用了不同的仿射变换。我想采取什么相当于我的UIView的屏幕截图,将其捕获为UIImage或其他图像表示形式。将UIViews子视图展平到UIImage iPhone 3.0

我已经试过了,层层渲染到CGContext上用的方法:

[view.layer renderInContext:UIGraphicsGetCurrentContext()]; 

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

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

回答

11

试试这个:

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

你去了。我只需要将self.view.size更改为self.view.frame.size并使用renderInContext。 我不知道我是如何错过这个的,我猜苹果公司文档中的关键词是“在图层的坐标空间中渲染”。 谢谢! – SooDesuNe 2009-09-15 01:09:49

+4

从iOS4开始,您应该使用UIGraphicsBeginImageContextWithOptions(size,NO,0.0) – steipete 2011-02-28 16:45:16

+0

如果您希望它不透明,请使用“YES”。如果你不需要阿尔法,有助于提高性能。 – 2012-03-17 01:21:46

0

这里有一个雨燕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 
}