iOS layer.mask 的原理

直接上原理

控制layer本身渲染的一个layer。效果是:比如imageLayer有一个maskLayer作为mask(注意maskLayer可以不跟imageLayer大小一样),那maskLayer透明的地方,imageLayer就不会渲染,而是变透明,显示出imageLayer之后的内容,maskLayer不透明的地方,imageLayer就会正常渲染,显示出imageLayer本来的内容如果maskLayer比imageLayer要小,那默认的maskLayer之外的地方都是透明的,都不会渲染。

由以上原理可知,如果我们想让一个视图只展示一部分,

那么我们可以通过设置其layer.mask来实现,

如果一个视图要实现一个渐变的展示,我们也可以通过

layer.mask实现

复制代码
   self.view.backgroundColor = [UIColor cyanColor];
    CALayer *layer = [[CALayer alloc] init];
    layer.frame = CGRectMake(100, 200, 100, 100);
    layer.backgroundColor = [UIColor whiteColor].CGColor;
    self.view.layer.mask = layer;

效果

整个页面只展示了一部分

复制代码
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor cyanColor];
  
    CAGradientLayer *gradientlayer = [[CAGradientLayer alloc] init];
    gradientlayer.frame = CGRectMake(100, 100, 100, 100);
    gradientlayer.colors = @[(id)[[UIColor whiteColor] colorWithAlphaComponent:0].CGColor, (id)[[UIColor whiteColor] colorWithAlphaComponent:1].CGColor];
    gradientlayer.locations = @[@0, @1];
    self.view.layer.mask = gradientlayer;
    // Do any additional setup after loading the view.
}
相关推荐
茶底世界之下12 小时前
灯塔照片怎么裁竖幅?用 Awaking 留住塔顶,收紧两侧环境
ios
庚鑫16 小时前
iOS 27 兼容放大模式下,keyboardFrame 与 UIScreen.bounds 的坐标差异
ios·objective-c
HEJOO917 小时前
iOS 高效绘图:从 Core Graphics 到 Metal 的实践指南
macos·ios·cocoa
HEJOO917 小时前
iOS 性能优化全面详解
ios·性能优化·cocoa
ii_best17 小时前
iOS 自动化脚本工具更新|按键精灵 适配 Relaxin(青霉素)越狱,兼容 iOS16~iOS26 主流越狱环境
ios·自动化·按键精灵
万年咸鱼17 小时前
iOS 27 适配笔记
笔记·ios·cocoa
HEJOO918 小时前
iOS Dark Mode 适配笔记
笔记·ios·cocoa
风雨_20 小时前
Mac M3 使用 OrbStack 全新安装运行 EasyConnect 完整教程
ios
Coder_张三2 天前
iOS 26 适配
前端·ios·swift
用户38034165882972 天前
崩溃率从 0.3% 到 0.04%:我们做对的不是修 bug,是让每个崩溃只发生一次
ios·swift