2010-06-27 28 views
14

我需要將UIView及其所有子視圖捕獲到UIImage中。問題是部分視圖不在屏幕上,所以我不能使用屏幕捕獲功能,並且當我嘗試使用UIGraphicsGetImageFromCurrentImageContext()函數時,它似乎也不捕獲子視圖。它應該捕獲子視圖,我只是做錯了什麼?如果沒有,有沒有其他的方式來完成這個?需要將UIView捕獲到UIImage中,包括所有子視圖

+0

我猜想,因爲每一個'UIView'是基於層的調用' - [CALayer的drawInContext:viewContext]'可能會有所幫助。 – 2010-06-28 00:47:33

回答

2

你的意思

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

不起作用?我敢肯定它應該...

27

這是正確的方式去:

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

這個方法是的UIImage類的擴展方法,它也將採取使圖像看起來的護理擅長任何未來的高分辨率設備。

+2

真的有效! – AlexeyVMP 2013-02-18 15:19:15

+0

保存我的時間:) 謝謝 – 2013-07-06 14:18:53

0

這裏有一個雨燕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 
} 
相關問題