2010-06-27 15 views
14

Necesito capturar una UIView y todas sus subvistas en un UIImage. El problema es que parte de la vista está fuera de la pantalla, por lo que no puedo usar la función de captura de pantalla, y cuando trato de usar la función UIGraphicsGetImageFromCurrentImageContext(), no parece capturar las subvistas también. ¿Debería capturar las subvistas y solo estoy haciendo algo mal? Si no, ¿hay alguna otra manera de lograr esto?Necesito capturar UIView en un UIImage, incluidas todas las subvistas

+0

supongo que ya que cada 'UIView' es llamada basada en capas '- [CALayer drawInContext: viewContext] 'podría ayudar. –

Respuesta

2

¿Quiere decir

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

no funciona? Estoy bastante seguro de que debería ...

27

Ese es el camino correcto a seguir:

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

Este método es un método de extensión para la clase UIImage, y también se encargará de hacer las miradas imagen bien en cualquier dispositivo futuro de alta resolución.

+2

¡Realmente funciona! – AlexeyVMP

+0

Ahorré mi tiempo :) Gracias –

0

Aquí hay una versión 2.x Swift que debería funcionar si primero se crea una matriz de los UIViews para ser aplanado:

// 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 
} 
Cuestiones relacionadas