在开发过程中,我们会遇到这样的需求,既要求控件有渐变的蒙层,还要不能遮挡控件的操作手势,例如下图这种效果
这种效果图的实现思路是 :在collectionview上面加一个渐变蒙层,蒙层从左至右加深透明度,从而实现最右侧遮挡的效果
废话不多说,直接上代码
//创建collectionview
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
layout.itemSize = CGSizeMake(AutoScaleWidth(80), AutoScaleWidth(100));
layout.minimumLineSpacing = 0;
layout.minimumInteritemSpacing = 10;
self.memberCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 100, AutoScaleWidth(100)) collectionViewLayout:layout];
self.memberCollectionView.delegate = self;
self.memberCollectionView.dataSource = self;
self.memberCollectionView.bounces = NO;
self.memberCollectionView.backgroundColor = HDColorFFFFFF;
self.memberCollectionView.showsHorizontalScrollIndicator = NO;
self.memberCollectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, AutoScaleWidth(20));
[self.memberCollectionView registerClass:[HDInnovationScoreGroupCollectionViewCell class] forCellWithReuseIdentifier:@"HDInnovationScoreGroupCollectionViewCell"];
[middleImageView addSubview:self.memberCollectionView];
[self.memberCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(middleImageView.mas_left).offset(AutoScaleWidth(19));
make.right.mas_equalTo(middleImageView.mas_right).offset(- AutoScaleWidth(11));
make.top.mas_equalTo(gropuLabel.mas_bottom).offset(AutoScaleWidth(10));
make.bottom.mas_equalTo(middleImageView.mas_bottom).offset(- AutoScaleWidth(10));
}];
//创建遮罩蒙层
self.layerView = [[UIView alloc] init];
self.layerView.userInteractionEnabled = NO;
self.layerView.backgroundColor = HDColorFFFFFF;
[middleImageView addSubview:self.layerView];
[self.layerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.memberCollectionView);
}
//设计遮罩蒙层的过度颜色,由于iOS直接两个颜色过度的话会产生较为明显的分界线,所以设计三个颜色进行渐变
UIColor *color1 = [UIColor colorWithRed:(0) green:(0) blue:(0) alpha:0];
UIColor *color2 = [UIColor colorWithRed:(0) green:(0) blue:(0) alpha:0.05 ];
UIColor *color3 = [UIColor colorWithRed:(0) green:(1) blue:(0) alpha:1.0];
NSArray *colors = [NSArray arrayWithObjects:(id)color1.CGColor, color2.CGColor,color3.CGColor, nil];
//设置颜色变换的位置节点
NSArray *locations = [NSArray arrayWithObjects:@(0.0), @(0.90),@(0.99), nil];
self.gradientLayer = [CAGradientLayer layer];
self.gradientLayer.colors = colors;
self.gradientLayer.locations = locations;
self.gradientLayer.frame =self.layerView.bounds;
self.gradientLayer.startPoint = CGPointMake(0, 0);
self.gradientLayer.endPoint = CGPointMake(1, 0);
self.layerView.layer.mask = self.gradientLayer;
注意事项
渐变色图层只有2个色值的渐变时,一般情况下设置2个颜色的渐变会导致图层中间某一部位颜色变化明显,渐变不流畅,我的经验是设置3~4个颜色,使渐变流畅