5

我在视图控制器的主视图中有一个水平滚动的 UICollectionView(灰色是 UIView,Wood 是 UICollectionView):

我想在这个 UICollectionView 的最左边和最右边添加固定的褪色渐变,这样当用户滚动时滚动看起来就会消失。我该怎么做呢?它是否涉及到 CAGradientLayer 的一些使用?如果您能给我任何帮助,我将不胜感激!

4

2 回答 2

8

多亏了cocoanetics 的本教程,我实际上设法使用一个遮罩层来解决这个问题。这是我所做的:

@interface ScalesViewController : UIViewController
{
    CAGradientLayer *maskLayer;
}
@end

然后在.m中,我放置了以下内容:

- (void)viewDidAppear:(BOOL)animated
{

    [super viewWillAppear: animated];

    if (!maskLayer)
    {
        maskLayer = [CAGradientLayer layer];

        CGColorRef outerColor = [[UIColor colorWithWhite:0.0 alpha:1.0] CGColor];
        CGColorRef innerColor = [[UIColor colorWithWhite:0.0 alpha:0.0] CGColor];

        maskLayer.colors = [NSArray arrayWithObjects:
                           (__bridge id)outerColor,
                           (__bridge id)innerColor,
                           (__bridge id)innerColor,
                           (__bridge id)outerColor, nil];

        maskLayer.locations = [NSArray arrayWithObjects:
                              [NSNumber numberWithFloat:0.0],
                              [NSNumber numberWithFloat:0.125],
                              [NSNumber numberWithFloat:0.875],
                              [NSNumber numberWithFloat:1.0], nil];

        [maskLayer setStartPoint:CGPointMake(0, 0.5)];
        [maskLayer setEndPoint:CGPointMake(1, 0.5)];

        maskLayer.bounds = self.mainCollectionView.bounds;
        maskLayer.anchorPoint = CGPointZero;

        [self.mainCollectionView.layer insertSublayer: maskLayer atIndex: 0];
    }
}

这会在我的集合视图的两侧创建一个很好的“淡入黑色”效果。可以将更多颜色添加到位置和颜色属性以优化渐变混合。起点/终点确定渐变的方向和位置。

于 2013-05-19T19:29:34.727 回答
1

尝试在集合视图子层上添加两层 CAGradientLayer:

#import <QuartzCore/QuartzCore.h>

CAGradientLayer *leftShadow = [CAGradientLayer layer];
leftShadow.frame = CGRectMake(0, 0, 100, self.collectionView.frame.size.height);
leftShadow.startPoint = CGPointMake(0, 0.5);
leftShadow.endPoint = CGPointMake(1.0, 0.5);
leftShadow.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:0.0 alpha:0.4f] CGColor], (id)[[UIColor clearColor] CGColor], nil];

[self.collectionView.layer addSublayer:leftShadow];

CAGradientLayer *rightShadow = [CAGradientLayer layer];
rightShadow.frame = CGRectMake(CGRectGetWidth(self.collectionView.frame)-100.0, 0, 100, self.collectionView.frame.size.height);
rightShadow.startPoint = CGPointMake(1.0, 0.5);
rightShadow.endPoint = CGPointMake(0, 0.5);
rightShadow.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:0.0 alpha:0.4f] CGColor], (id)[[UIColor clearColor] CGColor], nil];

[self.collectionView.layer addSublayer:rightShadow];
于 2013-05-19T08:50:28.033 回答