2010-10-23 20 views
6

Necesito oscurecer un UIImageView cuando se toca, casi exactamente como los iconos en el trampolín (pantalla de inicio).cómo oscurecer un UIImageView

Debería agregarse UIView con un fondo de 0.5 alfa y negro. Esto parece torpe Debería estar usando capas o algo (CALayers).

+0

¿Es posible utilizar un 'UIButton' en su lugar? –

Respuesta

4

¿Qué le parece subclasificar UIView y agregar un UIImage ivar (imagen llamada)? Luego, puede anular -drawRect: algo así, siempre que tenga un booleano ivar llamado presionado que se configuró al tocarlo.

- (void)drawRect:(CGRect)rect 
{ 
[image drawAtPoint:(CGPointMake(0.0, 0.0))]; 

// if pressed, fill rect with dark translucent color 
if (pressed) 
    { 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGContextSaveGState(ctx); 
    CGContextSetRGBFillColor(ctx, 0.5, 0.5, 0.5, 0.5); 
    CGContextFillRect(ctx, rect); 
    CGContextRestoreGState(ctx); 
    } 
} 

Desea experimentar con los valores RGBA anteriores. Y, por supuesto, las formas no rectangulares requerirían un poco más de trabajo, como un CGMutablePathRef.

+1

El UIImage en cuestión pasa a estar en una subclase UIView ya que puedo hacerlo. Sin embargo, ¿por qué iba a hacer esto en el método drawRect, no podría hacerlo directamente en los toques comenzó? –

+0

Si se trata de alternar algunos ajustes, entonces eso ocurrirá en touchesBegan. Y podría ser revertido en toques Ended. Pero creo que el dibujo real ocurrirá en drawRect. Es posible que necesite llamar a setNeedsDisplay en su instancia de subclase UIView junto con cambios de estado alternado. (Esto se puede hacer mejor en setter personalizado). No estoy seguro de cómo se comportaría una subclase de UIImageView si se reemplazara drawRect. Es por eso que sugerí el enfoque 'más seguro' de básicamente escribir tu propio UIImageView. Espero que esto ayude. – westsider

+0

ha entendido mal mi comentario, ¿por qué debe el dibujo personalizado pasar en drawRect. Por qué no puedo poner todo el CGContext ... Code in touchesBegan. –

1

UIImageView puede tener varias imágenes; podría tener dos versiones de la imagen y cambiar a la más oscura cuando sea necesario.

6

Dejaría que un UIImageView maneje el dibujo real de la imagen, pero alternar la imagen a una que haya sido oscurecida de antemano. Aquí hay un código que he usado para generar imágenes oscuras con alpha mantenido:

+ (UIImage *)darkenImage:(UIImage *)image toLevel:(CGFloat)level 
{ 
    // Create a temporary view to act as a darkening layer 
    CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height); 
    UIView *tempView = [[UIView alloc] initWithFrame:frame]; 
    tempView.backgroundColor = [UIColor blackColor]; 
    tempView.alpha = level; 

    // Draw the image into a new graphics context 
    UIGraphicsBeginImageContext(frame.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    [image drawInRect:frame]; 

    // Flip the context vertically so we can draw the dark layer via a mask that 
    // aligns with the image's alpha pixels (Quartz uses flipped coordinates) 
    CGContextTranslateCTM(context, 0, frame.size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 
    CGContextClipToMask(context, frame, image.CGImage); 
    [tempView.layer renderInContext:context]; 

    // Produce a new image from this context 
    CGImageRef imageRef = CGBitmapContextCreateImage(context); 
    UIImage *toReturn = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef); 
    UIGraphicsEndImageContext(); 
    [tempView release]; 
    return toReturn; 
} 
+0

¡Gracias! Esto es lo que estoy buscando. – VietHung

Cuestiones relacionadas