Domanda

Ho un UIView che ha diverse UIImageViews come sottoview. A ciascuna di queste sottopagine è stata applicata una trasformazione affine diversa. Vorrei prendere ciò che equivale a una cattura dello schermo del mio UIView, catturandolo come un UIImage o qualche altra rappresentazione di immagine.

Il metodo che ho già provato, il rendering dei layer in un CGContext con:

[view.layer renderInContext:UIGraphicsGetCurrentContext()];

non conserva il posizionamento o altre trasformazioni affini delle mie visualizzazioni secondarie.

Gradirei davvero un calcio nella giusta direzione.

È stato utile?

Soluzione

Prova questo:

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

Altri suggerimenti

Ecco una versione di 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
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top