Acoplar subvistas de UIViews a UIImage iPhone 3.0
-
07-07-2019 - |
Pregunta
Tengo una UIView que tiene varias UIImageViews como subvistas. Cada una de estas subvistas ha tenido diferentes transformaciones afines aplicadas. Me gustaría tomar lo que equivale a una captura de pantalla de mi UIView, capturarlo como un UIImage o alguna otra representación de imagen.
El método que ya he probado, representando las capas en un CGContext con:
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
no conserva el posicionamiento u otras transformaciones afines de mis subvistas.
Realmente agradecería una patada en la dirección correcta.
Solución
Prueba esto:
UIGraphicsBeginImageContext(self.view.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Otros consejos
Aquí hay una versión 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
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow