CALayer属性mask

CALayer的属性mask,mask也是一个layer,这边称它为maskLayer。介绍中描述

An optional layer whose alpha channel is used to mask the layer’s content.
The layer’s alpha channel determines how much of the layer’s content and background shows through. Fully or partially opaque pixels allow the underlying content to show through but fully transparent pixels block that content.

maskLayer的alpha值决定其内容和背景有多少显示。不透明和半透明的地方可以让其内容显示,透明的地方内容不显示;先举个栗子

test 1

- (void)setUpGradientLayerWithNotTransport
{
    //创建一个view,背景颜色是灰色
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    view.backgroundColor = [UIColor grayColor];
    [self.view addSubview:view];
    
    //采用CAGradientLayer实现颜色渐变,来测试是不是transport会让内容消失
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake((kScreenWidth - 100)/2,(kScreenHeight -100)/2 , 100, 100);
    
    //设置三种颜色,黑、红、透明
    [gradientLayer setColors:[NSArray arrayWithObjects:
                             (id)[[UIColor blackColor] CGColor],
                             (id)[[UIColor redColor] CGColor],
                             (id)[[UIColor clearColor] CGColor],
                             nil]];
    
    [gradientLayer setLocations:[NSArray arrayWithObjects:@0.0f, @0.5f, @1.0f, nil]];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(0, 1.0f);
    
    //设置view的mask
    [view.layer setMask:gradientLayer];
}

运行结果如下:

CALayer属性mask_第1张图片
屏幕快照 2016-07-29 下午3.29.59.png

原本view是整个屏幕大小,背景是灰色;gradientLayer是屏幕中心一个100*100的正方形,其颜色值最后一个是[UIColor clearColor],alpha值为0,而其余两个颜色值alpha值为1,可以从图中看到view只有中心一块显示,并且底部有白色渐变。

test 2

如果将gradientLayer的颜色换掉,替换代码如下:

    //设置三种颜色,黑、红、黄
    [gradientLayer setColors:[NSArray arrayWithObjects:
                              (id)[[UIColor blackColor] CGColor],
                              (id)[[UIColor redColor] CGColor],
                              (id)[[UIColor clearColor] CGColor],
                              nil]];

运行结果如下:

CALayer属性mask_第2张图片
屏幕快照 2016-07-29 下午3.32.21.png

view只有中心一块显示,但是全是灰色,没有渐变,因为三个颜色的alpha都为1,layer的内容全部显示。

test 3

让结果更直观可见,可以选择

    gradientLayer.backgroundColor = [[UIColor colorWithRed:0.716 green:1.000 blue:0.536 alpha:0.3] CGColor];
    //这边不需要用gradientLayer;可以用普通Layer
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake((kScreenWidth - 100)/2,(kScreenHeight -100)/2 , 100, 100);
    layer.backgroundColor = ([[UIColor colorWithRed:1.000 green:0.320 blue:0.608 alpha:0.259] CGColor]);

直接改变alpha通道,可以发现layer的原内容主体颜色不变,通透度变化,这边插播一个xcode中方便选取颜色的插件ColorSense

注意点
The layer you assign to this property must not have a superlayer. If it does, the behavior is undefined.

你可能感兴趣的:(CALayer属性mask)