Darken view as if disabled
ios, uibutton, uiview
Solution
What I'm currently playing with:
- Create a black layer with opacity (`_highlightLayer`). This is similar to the "black view with alpha" approach.
- Mask `_highlightLayer` with an non-opaque image of the original view.
- Add the `_highlightLayer` to the view's layer.
Only the non-transparent pixels of the view will be darkened.
The code:
- (void)highlight
{
// Black layer with opacity
_highlightLayer = [CALayer layer];
_highlightLayer.frame = CGRectMake(0, 0, self.layer.bounds.size.width, self.layer.bounds.size.height);
_highlightLayer.backgroundColor = [UIColor blackColor].CGColor;
_highlightLayer.opacity = 0.5;
// Create an image from the view
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *maskImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Create a mask layer for the black layer
CALayer *maskLayer = [CALayer layer];
maskLayer.contents = (__bridge id) maskImage.CGImage;
maskLayer.frame = _highlightLayer.frame;
_highlightLayer.mask = maskLayer;
[self.layer addSublayer:_highlightLayer];
}
And then:
- (void)unhighlight
{
[_highlightLayer removeFromSuperlayer];
_highlightLayer = nil;
}
Of course, this should only be used for small views.
Problem
How do you darken a view as if it were disabled/highlighted, preferably without using any additional views? By view I mean a `UIView`, with all its children. I want to achieve the same effect of a disabled/highlighted `UIButton`. Do not assume that the view is fully opaque.