How to darken UIImageView

I need to darken the UIImageView when it touches, almost exactly the same as the icons on the diving board (home screen).

Should I add a UIView with 0.5 alpha and a black background. It seems awkward. Should I use layers or something (CALayers).

+6
objective-c iphone uiimageview layer
source share
3 answers

What about subclassing UIView and adding a UImage ivar (called image)? Then you can override -drawRect: something like this if you have a boolean ivar pressed that was set when touched.

- (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); } } 

You would like to experiment with the RGBA values ​​above. And, of course, non-rectangular shapes will require a bit more work - for example, CGMutablePathRef.

+4
source share

I would allow UIImageView to handle the actual image drawing, but switched the image to the one that was darkened in advance. Here is some code that I used to create alpha-enabled darkened images:

 + (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 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; } 
+6
source share

UIImageView can have multiple images; You could have two versions of the image and switch to a darker one when necessary.

+1
source share

All Articles