您的位置:首页 > 其它

有淡入效果3D效果的scrollView

2015-12-26 12:20 127 查看
最近在工作中,有一个3D淡入效果的ScrollView,参考了网上的demo,但是网上的没有实现滚轴效果,就是类似pickerView的效果,自己花了点时间,将网上的demo改了一下实现了这样的效果,

demo演示效果如下:



大家可以看到无论滚动到哪里,主要选中某一个选中项,这个选中项就会滚动到中间的位置。

下面对核心代码进行分析。大家可以看到,scrollView两边,白色有边缘区域到中间逐渐淡化,这个主要是利用了CAGradientLayer来实现渐变。代码如下:

- (void)applyGradient
{
if (self.leftMask) {
[self.leftMask removeFromSuperview];
self.leftMask = nil;
}

if (self.rightMask) {
[self.rightMask removeFromSuperview];
self.rightMask = nil;
}

self.leftMask = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width / 2, self.frame.size.height)];
self.leftMask.userInteractionEnabled = NO;
self.leftMask.backgroundColor = self.gradientColor;
self.leftMask.alpha = 0;
[self insertSubview:self.leftMask aboveSubview:self.scrollView];

self.leftMask.layer.mask = [self gradientLayerForBounds:self.leftMask.bounds inVector:CGVectorMake(0.0, self.gradientPercentage) withColors:@[self.gradientColor, [UIColor clearColor]]];

self.rightMask = [[UIView alloc] initWithFrame:CGRectMake(self.frame.size.width / 2, 0, self.frame.size.width / 2, self.frame.size.height)];
self.rightMask.userInteractionEnabled = NO;
self.rightMask.backgroundColor = self.gradientColor;
self.rightMask.alpha = 0;
[self insertSubview:self.rightMask aboveSubview:self.scrollView];

self.rightMask.layer.mask = [self gradientLayerForBounds:self.rightMask.bounds inVector:CGVectorMake(1 - self.gradientPercentage, 1.0) withColors:@[[UIColor clearColor], self.gradientColor]];
}


左右两个mask,颜色clearColor,whiteColor两种颜色紫之间进行过渡,关于CAGradientLayer的具体使用方法请看我的这篇博客CAGradientLayer简介

这里面讲的很详细。

另外就是关于选中项居中的问题,这个问题其实困惑了我很久,我这里主要的思路就是让第一个button的frame为origin.x为self.scrollView.frame.width/2,然后self.scrollView.contentsize的width,也增加self.scrollView.frame.width/2 这么多,这样每次选中的时候,我通过改变self.scrollView的偏移量来实现选中项居中显示,也就是有点像pickerview的效果的。

关键代码如下:

- (void)scrollItemVisible:(UIButton *)item
{

NSInteger index =item.tag;
NSLog(@"index %d",(int)index);
CGRect frame = CGRectMake((index)*92+15, 0, self.frame.size.width, self.frame.size.width);
[self.scrollView scrollRectToVisible:frame animated:YES];
}


这俩面的数据,其实是自己一点一点试出来的,总觉得没有理论的支持,不是太踏实,CGRectMake((index)*92+15, 0, self.frame.size.width, self.frame.size.width); 大家这个地方如果有看的比较明白的话,可以提出好的意见哦。谢谢了

demo下载地址:demo
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息