不要讓 superview 的 alpha 影響到 subview

在項(xiàng)目開發(fā)當(dāng)中,有的時(shí)候可能會(huì)遇到這么一個(gè)需求,UI 設(shè)計(jì)師希望在一個(gè)半透明的背景 View 上面顯示一些內(nèi)容,這個(gè)是一個(gè)挺常見的需求,不知道你有沒有碰到過,我是一直都有碰到這個(gè)需求。

拿到需求一看,這個(gè)需求實(shí)現(xiàn)起來非常簡(jiǎn)單的,三下五除二,敲了一大段代碼,在 View 上面添加一個(gè) backgroundView,并在 backgroundView 上面添加一個(gè) imageView。

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UIView *backgroundView;
@property (nonatomic,strong) UIImageView *imageView;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 背景
    self.backgroundView = [[UIView alloc] init];
    UIColor *backgroundColor =  [UIColor colorWithRed : ((0x242424 >> 16) & 0xFF) / 255.0 green : ((0x242424 >> 8) & 0xFF) / 255.0 blue : (0x242424 & 0xFF) / 255.0 alpha : 1.0];
    self.backgroundView.backgroundColor = backgroundColor;
    self.backgroundView.frame = self.view.frame;
    [self.view addSubview:self.backgroundView];
    
    
    // 圖片
    CGFloat x = (self.view.frame.size.width - 100) *0.5;
    self.imageView = [[UIImageView alloc] init];
    self.imageView.frame = CGRectMake(x, 50, 100, 100);
    [self.imageView setImage:[UIImage imageNamed:@"center_video_local"]];
    [self.backgroundView addSubview:self.imageView];
}
@end

代碼寫的差不多了,運(yùn)行查看結(jié)果。UI 樣式都是可以的,但是背景黑乎乎的,少了個(gè)透明度,沒關(guān)系,這個(gè)簡(jiǎn)單,給個(gè) alpha 屬性就 ok 了。


image.png

看看我們給了 alpha 屬性之后的代碼,運(yùn)行查看效果。

    // 背景
    self.backgroundView = [[UIView alloc] init];
    // 增加 alpha 屬性
    self.backgroundView.alpha = 0.3;

有沒有發(fā)現(xiàn)問題了?設(shè)置了 backgroudView 的 alpha 屬性之后,backgroudView 的 subview 也受影響了,這個(gè)顯然不是我們想要的結(jié)果,我們希望 alpha 屬性只作用于 backgroudView。


image.png

經(jīng)過一番搜索,找到了這么一個(gè)信息。alpha 屬性會(huì)作用于 backgroudView 和 它的 subview,UIColor 的 alpha 只會(huì)作用于 View 本身。從這個(gè)知識(shí)點(diǎn)中可以得出,如果設(shè)置 backgroudView 的 backgroundColor 的 alpha 屬性就可以避免 alpha 屬性作用于 subview。

修改代碼,運(yùn)行查看結(jié)果,正符合我們的預(yù)期。

 // 背景
    self.backgroundView = [[UIView alloc] init];
    // 去掉 alpha 屬性
    //  self.backgroundView.alpha = 0.3;
    // 使用 UIColor 的 alpha 屬性
    UIColor *backgroundColor =  [UIColor colorWithRed : ((0x242424 >> 16) & 0xFF) / 255.0 green : ((0x242424 >> 8) & 0xFF) / 255.0 blue : (0x242424 & 0xFF) / 255.0 alpha : 0.3];
image.png

參考

  1. https://stackoverflow.com/questions/10892535/not-to-update-the-subview-with-superview-alpha-value
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容