在開發(fā)過程中乾翔,我們會(huì)遇到這樣的需求爱葵,既要求控件有漸變的蒙層,還要不能遮擋控件的操作手勢末融,例如下圖這種效果
這種效果圖的實(shí)現(xiàn)思路是 :在collectionview上面加一個(gè)漸變蒙層钧惧,蒙層從左至右加深透明度暇韧,從而實(shí)現(xiàn)最右側(cè)遮擋的效果
廢話不多說勾习,直接上代碼
//創(chuàng)建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));
}];
//創(chuàng)建遮罩蒙層
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);
}
//設(shè)計(jì)遮罩蒙層的過度顏色,由于iOS直接兩個(gè)顏色過度的話會(huì)產(chǎn)生較為明顯的分界線懈玻,所以設(shè)計(jì)三個(gè)顏色進(jìn)行漸變
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];
//設(shè)置顏色變換的位置節(jié)點(diǎn)
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;
注意事項(xiàng)
漸變色圖層只有2個(gè)色值的漸變時(shí)巧婶,一般情況下設(shè)置2個(gè)顏色的漸變會(huì)導(dǎo)致圖層中間某一部位顏色變化明顯乾颁,漸變不流暢,我的經(jīng)驗(yàn)是設(shè)置3~4個(gè)顏色艺栈,使?jié)u變流暢