2011-01-19 30 views
13

Tengo un UIView y yo quiero que se pueda almacenar como un PNG transparente, es decir, sin el color de fondo UIView ...Guardar UIView a un PNG transparente

actualmente estoy usando este código y que está funcionando bien, pero con el color de fondo :(

UIGraphicsBeginImageContext(self.bounds.size); 
[self.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage* image1 = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image1); 
[imageData writeToFile:filePath atomically:YES]; 

Así que, ¿alguien tiene alguna idea acerca de cómo obtener esta imagen como una transparente?

gracias de antemano ..

+1

intenta establecer el color de fondo de la vista a [UIColor clearColor]; –

+2

gracias por su respuesta, el punto es que quiero que el usuario vea el fondo y quiero generar la imagen y almacenarla en los documentos mientras la aplicación se está ejecutando :( –

+0

¿Alguna vez hizo que esto funcione? Necesito para hacer algo similar. – Travis

Respuesta

7

Cambiar el ba Seleccione el color para [UIColor clear], dibuje la imagen y luego ajuste el color de fondo al color original.

Como las actualizaciones de la GUI se dispararán solo en el próximo ciclo de ciclo de ejecución, el usuario no debería ver ningún parpadeo.

UIColor* color=self.backgroundColor; 
view.backgroundColor=[UIColor clearColor]; 

UIGraphicsBeginImageContext(self.bounds.size); 
[self.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage* image1 = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image1); 
[imageData writeToFile:filePath atomically:YES]; 

self.backgroundColor=color; 
2

Además de la respuesta de Gilad. En la pantalla Retina esto puede causar algunos problemas de calidad. Para obtener el contexto de la retina, puede usar este código desde la publicación this.

UIColor* color=self.backgroundColor; 
view.backgroundColor=[UIColor clearColor]; 

// This is for retina render check 
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow]; 
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) 
    UIGraphicsBeginImageContextWithOptions(YourView.frame.size, NO, [UIScreen mainScreen].scale); 
else 
    UIGraphicsBeginImageContext(keyWindow.bounds.size); 
// And it goes up to here the rest stays the same 

[self.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage* image1 = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image1); 
[imageData writeToFile:filePath atomically:YES]; 

self.backgroundColor=color; 
9

En mi caso, olvidé la propiedad opaca. Cabe establece en NO:

view.opaque = NO; 
+0

¡Este era el eslabón perdido! Utilicé esta (http://stackoverflow.com/a/22494886/251394) respuesta para guardar la imagen. – srik

+0

¡Esto funcionó para mí! – bodagetta

0

Por Objetivo-c usted tiene que fijar opaca = NO

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

Para Swift tiene que establecer opaca = false

func imageWithView(inView: UIView) -> UIImage? { 
     UIGraphicsBeginImageContextWithOptions(inView.bounds.size, false, 0.0) 
     if let context = UIGraphicsGetCurrentContext() { 
      inView.layer.render(in: context) 
      let image = UIGraphicsGetImageFromCurrentImageContext() 
      UIGraphicsEndImageContext() 
      return image 
     } 
     return nil 
    } 
Cuestiones relacionadas