views:

129

answers:

2

I'd like to "darken" a UIView by a certain amount. Right now, I'm doing the darkening like this:

UIView *overlay = [[UIView alloc] initWithFrame:mainView.bounds];
overlay.backgroundColor = [UIColor blackColor];
overlay.alpha = 0.5f;
[mainView addSubview:overlay];

Unfortunately, this also adds a semi-transparent black overlay to parts of mainView that are transparent. Is there any way to only darken the non-transparent sections?

A: 

Try using something like this (adjust the colors, obviously)?

overlay.backgroundColor = [UIColor colorWithRed:0.317647 green:0.317647 blue:0.317647 alpha:0.85];

psychotik
Wouldn't you set the background color to (0, 0, 0, 0.85)?
chpwn
A: 

Here is something to try. I have never used UIRectFillUsingBlendMode.

-(void) drawRect:(CGRect)inDirty {
  [[UIColor colorWithWhite:0.0 alpha:0.5] setFill];
  UIRectFillUsingBlendMode( inDirty , kCGBlendModeDarken );
}

The view implementing this would have to be set up to composite with only the other views you want to affect. That probably means one parent view that contains this view and all the other views you want to darken.

You can also look into CGContextSetBlendMode.

drawnonward
This looks promising! I'm not sure what you mean about compositing with other views, though (I'm a UIView noob). In my example, could I just override drawRect: in mainView?
igul222
The blend mode darken will darken everything else that has already been drawn in the same context. That means whatever views you want to darken must already have drawn into the same context you are about to draw into. Control of the current context in `drawRect:` is up to the system, and I am not sure how it does things. If it makes a brand new context for each view, then this code will might do nothing at all. If this does not work, you could render the view to darken into an image, then draw the image and darken it as above.
drawnonward