需要通过一个mask图显示部分UI或者Icon资源。ios的控件自带alpha的值,但是这个值都是整个icon或者UI的透明效果,不能做到自定义的透明或者镂空效果。我们必须借助于mask资源图。
具体的方法:修改imageview的layer,即可完成这个工作。
CALayer *mask = [CALayer layer];
mask.contents = (id)[[UIImage imageNamed:@"mask.png"] CGImage];
mask.frame = CGRectMake(0, 0, <img_width>, <img_height>);
yourImageView.layer.mask = mask;
yourImageView.layer.masksToBounds = YES;
//MARK:1. maskView(maskLayer)基本原理
CGFloat width = 120.f;
//底图
self.baseImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, width, width)];
[_baseImageView setImage:[UIImage imageNamed:@"base"]];
[self.view addSubview:_baseImageView];
//mask 是有透明的
self.maskImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20 + width + 20, width, width)];
[_maskImageView setImage:[UIImage imageNamed:@"mask"]];
[self.view addSubview:_maskImageView];
//使用maskView的情况
self.addImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20 + (width + 20) * 2, width, width)];
[_addImageView setImage:[UIImage imageNamed:@"base"]];
UIImageView *mask = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, width)];
[mask setImage:[UIImage imageNamed:@"mask"]];
[_addImageView setMaskView:mask];//iOS8.0之后才有 maskView不能用addSubView的方式来添加遮罩!!!
/*iOS 8之前
// CALayer *layer = [CALayer layer];
// [layer setFrame:CGRectMake(0, 0, width, width)];
// [layer setContents:(id)[UIImage imageNamed:@"mask"].CGImage];
// [_addImageView.layer setMask:layer];
*/
[self.view addSubview:_addImageView];