maskView基本原理
png圖片透明像素的原理 maskView可類比于多張png圖片的疊加遮罩,原理類似 maskView是iOS8以上才有的,如果要考慮兼容低版本,用maskLayer替代
@property (nonatomic , strong )UIImageView *addImageView; self .addImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50 , 50 , 200 , 200 )];[self .view addSubview:self .addImageView ];
self .addImageView .image = [UIImage imageNamed:@"base" ];
UIImageView *mask = [[UIImageView alloc]initWithFrame:CGRectMake(0 , 0 , 200 , 200 )];
mask.image = [UIImage imageNamed:@"mask" ];
self .addImageView .maskView = mask;
注意:maskView并不能用addSubview來添加遮罩
maskView配合CAGradientLayer的使用
用CAGradientLayer直接產生帶透明像素通道的layer 用maskView直接加載帶CAGradientLayer的view 可以通過對CAGradientLayer進行動畫的操作實現動畫效果
看實例代碼
self .addImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50 , 450 , 200 , 200 )];[self .view addSubview:self .addImageView ];self .addImageView .image = [UIImage imageNamed:@"base" ];CAGradientLayer *gradientLayer = [CAGradientLayer layer];gradientLayer.frame = self .addImageView .bounds ;gradientLayer.colors = @[(__bridge id )[UIColor clearColor].CGColor ,(__bridge id )[UIColor blackColor].CGColor ,(__bridge id )[UIColor clearColor].CGColor ];gradientLayer.locations = @[@(0.05 ),@(0.5 ),@(0.95 )];gradientLayer.startPoint = CGPointMake(0 , 0 );gradientLayer.endPoint = CGPointMake(1 , 0 );UIView *containerView = [[UIView alloc]initWithFrame:self .addImageView .bounds ];[containerView.layer addSublayer:gradientLayer];self .addImageView .maskView = containerView;CGRect frame = containerView.frame ;frame.origin .x -=200 ;containerView.frame = frame;[UIView animateWithDuration:3. f animations:^{CGRect frame = containerView.frame ;frame.origin .x += 400 ;containerView.frame = frame;}];
我們不僅可以使用CAGradientLayer創建的蒙版,我們還可以對他進行動畫效果的設置