使视图变暗,好像已禁用 [英] Darken view as if disabled

查看:51
本文介绍了使视图变暗,好像已禁用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使视图变暗(好像已被禁用/突出显示),最好不使用任何其他视图?

How do you darken a view as if it were disabled/highlighted, preferably without using any additional views?

按视图,我指的是 UIView ,其中包含所有子项.我想获得禁用/突出显示的 UIButton 的相同效果.

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.

推荐答案

我目前正在玩的游戏:

  1. 创建不透明的黑色图层( _highlightLayer ).这类似于带有alpha的黑色视图"方法.
  2. 用原始视图的不透明图像掩盖 _highlightLayer .
  3. _highlightLayer 添加到视图的图层.
  1. Create a black layer with opacity (_highlightLayer). This is similar to the "black view with alpha" approach.
  2. Mask _highlightLayer with an non-opaque image of the original view.
  3. Add the _highlightLayer to the view's layer.

仅视图的非透明像素将变暗.

Only the non-transparent pixels of the view will be darkened.

代码:

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

然后:

- (void)unhighlight
{
    [_highlightLayer removeFromSuperlayer];
    _highlightLayer = nil;
}

当然,这仅应用于较小的视图.

Of course, this should only be used for small views.

这篇关于使视图变暗,好像已禁用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆