superviewに影響を受けないsubviewのalpha設定方法

今日はUIViewの話をしたいと思います。

まずは、今回の題材となるコードを見ていただきましょう。

UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
aView.alpha = 0.5;
[self.view addSubview:aView];
        
UIView *bView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
bView.backgroundColor = [UIColor redColor];
[aView addSubview:bView];

このコードでは赤いbViewはaViewのalphaに影響を受けてしまい半透明になってしまいます。

これをbViewのsuperviewをaViewに保ったままalphaが1.0のbViewにする方法があるのです。

それがこちらのコード。

UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
aView.layer.shouldRasterize = YES;
aView.alpha = 0.5;
[self.view addSubview:aView];
        
UIView *bView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
bView.backgroundColor = [UIColor redColor];
[aView addSubview:bView];

親viewのlayer.shouldRasterizeをYESにすれば解決!
aViewのsubviewにalphaを伝えない様にする事が可能になります。

このプロパティを知るまではやむを得ずaViewとbViewの親子関係を兄弟関係にしていました。
([aView addSubview:bView];ではなく、[self.view addSubview:bView];)
これでそんな気持ち悪い事はしなくて済みそうです。

誰かのお役に立てば。

コメント

タイトルとURLをコピーしました