What I'm playing with:
- Create a black layer with opacity (
_highlightLayer ). This is similar to the black view with alpha approach. _highlightLayer mask with an opaque image of the original view.- Add
_highlightLayer to the presentation layer.
Only opaque view pixels will be darkened.
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.
source share