2011-07-11 12 views
19

¿Es posible agregar otra imagen más pequeña a un UIImage/UIImageView? ¿Si es así, cómo? Si no, ¿cómo puedo dibujar un triángulo pequeño lleno?Dibuje otra imagen en un UIImage

Gracias

Respuesta

36

Se podría añadir una vista secundaria a su UIImageView contiene otra imagen con el pequeño triángulo relleno. O podría dibujar en el interior de la primera imagen:

CGFloat width, height; 
UIImage *inputImage; // input image to be composited over new image as example 

// create a new bitmap image context at the device resolution (retina/non-retina) 
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), YES, 0.0);   

// get context 
CGContextRef context = UIGraphicsGetCurrentContext();  

// push context to make it current 
// (need to do this manually because we are not drawing in a UIView) 
UIGraphicsPushContext(context);        

// drawing code comes here- look at CGContext reference 
// for available operations 
// this example draws the inputImage into the context 
[inputImage drawInRect:CGRectMake(0, 0, width, height)]; 

// pop context 
UIGraphicsPopContext();        

// get a UIImage from the image context- enjoy!!! 
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext(); 

// clean up drawing environment 
UIGraphicsEndImageContext(); 

Este código (source here) va a crear un nuevo UIImage que se puede utilizar para inicializar un UIImageView.

20

Puede probar esto, funciona perfecto para mí, es la categoría UIImage:

- (UIImage *)drawImage:(UIImage *)inputImage inRect:(CGRect)frame { 
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0); 
    [self drawInRect:CGRectMake(0.0, 0.0, self.size.width, self.size.height)]; 
    [inputImage drawInRect:frame]; 
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return newImage; 
} 

o Swift:

extension UIImage { 
    func image(byDrawingImage image: UIImage, inRect rect: CGRect) -> UIImage! { 
     UIGraphicsBeginImageContext(size) 
     draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) 
     image.draw(in: rect) 
     let result = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return result 
    } 
} 
+0

Gracias amigo, que es un fragmento muy útil. –

+1

Esto funciona bien, gracias. Sin embargo, sugiero que uses 'UIGraphicsBeginImageContextWithOptions (size, false, 0)'. Esto le dará una imagen con la resolución correcta para la pantalla. (El valor predeterminado solo producirá una imagen x1, que seguramente será borrosa). – Womble

Cuestiones relacionadas