2010-10-06 9 views
9

Tengo un UIImageView con millones de vistas. Algunas de estas vistas tienen sombras de capa o brillo. Esta vista es un poco más grande que la pantalla del dispositivo.iPhone - allanando un UIImageView y subvistas a la imagen = imagen en blanco

Este punto de vista es básicamente una visión transparente grande que contiene muchos objetos (imágenes, botones, etc.)

ahora quiero aplanar todo en ese punto de vista a un UIImage. Entonces, lo hago:

UIGraphicsBeginImageContext([viewWithZillionsOfObjects bounds].size); 
[[viewWithZillionsOfObjects layer] renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

resultado es igual a una imagen totalmente transparente, pero tiene el tamaño correcto.

¿echo en falta algo?

gracias

+0

Este código funciona: http://stackoverflow.com/questions/3129352/need-to-capture-uiview-into-a-uiimage-including-all-subviews – AlexeyVMP

+0

Este núcleo realmente funciona: http://stackoverflow.com/questions/3129352/need-to-capture-uiview-into-a-uiimage-including-all-subviews – AlexeyVMP

Respuesta

19

En el código de ejemplo de Apple, ajustan la geometría del contexto gráfico para que coincida con la geometría de la capa antes de llamar renderInContext:.

Se trata de una ventana, pero parece que el código debería funcionar con cualquier vista con algunos cambios menores.

No he intentado construir esto, pero aquí está mi intento de cambiar el código de Apple para trabajar en cualquier vista.

- (UIImage*)imageFromView:(UIView *)view 
{ 
    // Create a graphics context with the target size 
    // On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration 
    // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext 
    CGSize imageSize = [view bounds].size; 
    if (NULL != UIGraphicsBeginImageContextWithOptions) 
     UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0); 
    else 
     UIGraphicsBeginImageContext(imageSize); 

    CGContextRef context = UIGraphicsGetCurrentContext(); 

    // -renderInContext: renders in the coordinate space of the layer, 
    // so we must first apply the layer's geometry to the graphics context 
    CGContextSaveGState(context); 
    // Center the context around the view's anchor point 
    CGContextTranslateCTM(context, [view center].x, [view center].y); 
    // Apply the view's transform about the anchor point 
    CGContextConcatCTM(context, [view transform]); 
    // Offset by the portion of the bounds left of and above the anchor point 
    CGContextTranslateCTM(context, 
          -[view bounds].size.width * [[view layer] anchorPoint].x, 
          -[view bounds].size.height * [[view layer] anchorPoint].y); 

    // Render the layer hierarchy to the current context 
    [[view layer] renderInContext:context]; 

    // Restore the context 
    CGContextRestoreGState(context); 

    // Retrieve the screenshot image 
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 

    UIGraphicsEndImageContext(); 

    return image; 
} 
+0

lo que necesito no es exactamente una captura de pantalla ... o renderizar una ventana, porque necesito renderizar específicamente lo que está en una vista y no en todas. Esperaba que la propiedad de la capa incluyera todo lo que es visible en una UIView determinada, pero curiosamente no es así. Gracias. – SpaceDog

+0

Creo que puede cambiar el código para operar en la vista que desee. Los bits de la ventana son incidentales. –

+0

He incluido el código para operar en cualquier vista. –

0

Aquí hay una versión general (Swift 2.x) para aplanar una matriz de UIViews en un solo UIImage. En su caso, simplemente pase una matriz que consta de una sola UIView, y debería funcionar.

// 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