views:

58

answers:

2

I need to darken a UIImageView when it gets touched, almost exactly like icons on the springboard (home screen).

Should I be added UIView with a 0.5 alpha and black background. This seems clumsy. Should I be using Layers or something (CALayers).

A: 

UIImageView can have multiple images; you could have two versions of the image and switch to the darker one when needed.

jamihash
+1  A: 

How about subclassing UIView and adding a UIImage ivar (called image)? Then you could override -drawRect: something like this, provided you had a boolean ivar called pressed that was set while 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 want to experiment with RGBA values above. And, of course, non-rectangular shapes would require a bit more work - like a CGMutablePathRef.

westsider
The UIImage on question happen to be in a subclasses UIView already so I can do this. However why would I do this in the drawRect method, couldn't I do it directly in the touches began?
Jonathan
If it's a matter of toggling some setting, then that would happen in touchesBegan. And it might be toggled back in touchesEnded. But the actual drawing would, I think, happen in drawRect. You might need to call setNeedsDisplay on your UIView subclass instance in conjunction with toggled state changes. (This might be best done in custom setter.) I am not sure how a subclass of UIImageView would behave if its drawRect were overridden. This is why I suggested the 'safer' approach of basically writing your own UIImageView. Hope this helps.
westsider
@westsider, you misunderstood my comment, why must the custom drawing happen in drawRect. Why I can't I put all the CGContext... Code in touchesBegan.
Jonathan
@Jonathan, to quote Joe Conway and Aaron Hillegass from page 91 of their book "iPhone Programming: The Big Nerd Ranch Guide", 'The drawRect: method is where the drawing code for the view goes.' I always do my Core Graphics drawing within drawRect:. You might want to read through this <http://developer.apple.com/library/ios/#documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/GraphicsandDrawing/GraphicsandDrawing.html%23//apple_ref/doc/uid/TP40009503-CH3-SW3> for more details. I have been unable to find docs that warn against drawing outside of drawRect:; thought I read something like that...
westsider