2011-02-22 9 views
67

Sé que puedes hacer esto con un UIImageView, pero ¿se puede hacer con un UIImage? Quiero que la propiedad de matriz de imágenes de animación de UIImageView sea una matriz de la misma imagen pero con diferentes opacidades. ¿Pensamientos?Cómo establecer la opacidad/alfa de un UIImage?

Respuesta

114

Solo necesitaba hacer esto, pero pensé que la solución de Steven sería lenta. Esto con suerte debería usar gráficos HW. Crear una categoría en UIImage:

- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha { 
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f); 

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGRect area = CGRectMake(0, 0, self.size.width, self.size.height); 

    CGContextScaleCTM(ctx, 1, -1); 
    CGContextTranslateCTM(ctx, 0, -area.size.height); 

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply); 

    CGContextSetAlpha(ctx, alpha); 

    CGContextDrawImage(ctx, area, self.CGImage); 

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 

    UIGraphicsEndImageContext(); 

    return newImage; 
} 
+2

ni siquiera puedo recordar por qué necesitaba esto :) – Marty

+0

¡Gran solución! Gracias Nick! – Christopher

+1

Solo asegúrese de estar llamando a UIGraphicsBeginImageContextWithOptions en el hilo principal porque la representación en segundo plano será impredecible. –

72

establecer la opacidad de su vista que se muestra en.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"SomeName.png"]]; 
imageView.alpha = 0.5; //Alpha runs from 0.0 to 1.0 

utilizar esto en una animación. Puedes cambiar el alfa en una animación por una duración.

[UIView beginAnimations:nil context:NULL]; 
[UIView setAnimationDuration:1.0]; 
//Set alpha 
[UIView commitAnimations]; 
+0

Sí, yo estaba pensando que podría tener que hacerlo de esta manera con un temporizador para cambiar la opacidad constante, sólo pensé que sería es mucho más fácil tener una matriz para la propiedad de la matriz de imágenes de animación para que se pueda animar por sí misma. – Marty

+0

Puede animarlo 'dentro' y 'fuera' como un latido con el delegado de animación. No use un temporizador, la animación cambiará el alfa sin problemas. Buena suerte. –

+3

Esto solo funciona si el desarrollador usa un UIImageView.La pregunta claramente dice que ese no es el caso. –

4

me di cuenta que es bastante tarde, pero necesitaba algo como esto, así que nos prepararon rápidamente un método rápido y sucio para hacer esto.

+ (UIImage *) image:(UIImage *)image withAlpha:(CGFloat)alpha{ 

    // Create a pixel buffer in an easy to use format 
    CGImageRef imageRef = [image CGImage]; 
    NSUInteger width = CGImageGetWidth(imageRef); 
    NSUInteger height = CGImageGetHeight(imageRef); 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

    UInt8 * m_PixelBuf = malloc(sizeof(UInt8) * height * width * 4); 

    NSUInteger bytesPerPixel = 4; 
    NSUInteger bytesPerRow = bytesPerPixel * width; 
    NSUInteger bitsPerComponent = 8; 
    CGContextRef context = CGBitmapContextCreate(m_PixelBuf, width, height, 
               bitsPerComponent, bytesPerRow, colorSpace, 
               kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); 
    CGContextRelease(context); 

    //alter the alpha 
    int length = height * width * 4; 
    for (int i=0; i<length; i+=4) 
    { 
     m_PixelBuf[i+3] = 255*alpha; 
    } 


    //create a new image 
    CGContextRef ctx = CGBitmapContextCreate(m_PixelBuf, width, height, 
               bitsPerComponent, bytesPerRow, colorSpace, 
               kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 

    CGImageRef newImgRef = CGBitmapContextCreateImage(ctx); 
    CGColorSpaceRelease(colorSpace); 
    CGContextRelease(ctx); 
    free(m_PixelBuf); 

    UIImage *finalImage = [UIImage imageWithCGImage:newImgRef]; 
    CGImageRelease(newImgRef); 

    return finalImage; 
} 
+2

Mejor nombre sería 'setImage: withAlpha:' – Alexander

+0

tan verdadero. gracias por la punta –

+8

conjunto generalmente se refieren a las propiedades, de alguna manera cambiar el estado del receptor. sería mejor llamarlo 'image: withAlpha:'? –

10

hay solución mucho más fácil:

- (UIImage *)tranlucentWithAlpha:(CGFloat)alpha 
{ 
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale); 
    [self drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:alpha]; 
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return image; 
} 
+1

Probablemente debería haber sido la respuesta aceptada. La manera más rápida/más eficiente de obtener el resultado –

26

Sobre la base de la respuesta de Alexey Ishkov, pero en Swift

que utiliza una extensión de la clase UIImage.

Swift 2:

UIImage Extensión:

extension UIImage { 
    func imageWithAlpha(alpha: CGFloat) -> UIImage { 
     UIGraphicsBeginImageContextWithOptions(size, false, scale) 
     drawAtPoint(CGPointZero, blendMode: .Normal, alpha: alpha) 
     let newImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return newImage 
    } 
} 

de usar:

let image = UIImage(named: "my_image") 
let transparentImage = image.imageWithAlpha(0.5) 

Swift 3:

Nótese que esta implementación retornos un UIImage opcional. Esto se debe a que en Swift 3 UIGraphicsGetImageFromCurrentImageContext ahora se devuelve un opcional. Este valor podría ser nulo si el contexto es nulo o no creado con UIGraphicsBeginImageContext.

UIImage Extensión:

extension UIImage { 
    func image(alpha: CGFloat) -> UIImage? { 
     UIGraphicsBeginImageContextWithOptions(size, false, scale) 
     draw(at: .zero, blendMode: .normal, alpha: alpha) 
     let newImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return newImage 
    } 
} 

de usar:

let image = UIImage(named: "my_image") 
let transparentImage = image?.image(alpha: 0.5) 
+0

Prefiero esta versión 'Swift 3'. – AechoLiu

3

Hey hey agradecimiento de usuario Xamarin! :) Aquí va traducido a C#

//*************************************************************************** 
public static class ImageExtensions 
//*************************************************************************** 
{ 
    //------------------------------------------------------------- 
    public static UIImage WithAlpha(this UIImage image, float alpha) 
    //------------------------------------------------------------- 
     { 
     UIGraphics.BeginImageContextWithOptions(image.Size,false,image.CurrentScale); 
     image.Draw(CGPoint.Empty, CGBlendMode.Normal, alpha); 
     var newImage = UIGraphics.GetImageFromCurrentImageContext(); 
     UIGraphics.EndImageContext(); 
     return newImage; 
     } 

} 

Ejemplo de uso:

var MySupaImage = UIImage.FromBundle("opaquestuff.png").WithAlpha(0.15f);