【问题标题】:Mask overlay on UIScrollViewUIScrollView 上的蒙版覆盖
【发布时间】:2011-04-18 22:16:07
【问题描述】:

您将如何在 UIScrollView 上覆盖各种蒙版图像?

例如,我有一张图像,左侧为黑色,右侧逐渐变为白色。我想使用它,以便滚动视图中的项目逐渐淡出到两侧,并且中心项目完全不透明。

此外,放置滚动视图的视图的背景是动态的并且可以更改的图像(不是纯色)。

有什么想法吗?

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    你的问题是我能找到的关于基本问题的最佳来源,所以我决定在这里发布我的解决方案。

    如果您直接将遮罩添加到滚动视图,您最终会出于某种原因将遮罩应用到内容本身——i。 e.滚动时透明度不会改变。根据其他帖子的建议,我将渐变放在(或者更确切地说,包含)滚动视图的视图中。因此,scrollContainer 是一个 UIViewObject,其唯一的子视图是相关的滚动视图。

    此掩码配置为从左到右滚动。您可以通过操作渐变的起点和终点属性将其从上到下更改。

    不利的一面是,这也会剪辑滚动视图的滚动位置栏指示器。由于我的场景不需要一个,这是可以接受的,但你的里程可能会有所不同。

    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = scrollView.bounds;
    gradient.colors = [NSArray arrayWithObjects:
                       (id)[[UIColor colorWithWhite:0 alpha:0] CGColor],
                       (id)[[UIColor colorWithWhite:0 alpha:1] CGColor],
                       (id)[[UIColor colorWithWhite:0 alpha:1] CGColor],
                       (id)[[UIColor colorWithWhite:0 alpha:0] CGColor], nil];
    gradient.locations=[NSArray arrayWithObjects:
                        [NSNumber numberWithFloat:0],
                        [NSNumber numberWithFloat:.1],
                        [NSNumber numberWithFloat:.9],
                        [NSNumber numberWithFloat:1], nil];
    gradient.startPoint=CGPointMake(0, .5);
    gradient.endPoint=CGPointMake(1, .5);
    [scrollContainer.layer setMask:gradient];
    

    【讨论】:

    • 确保你的链接框架和库中有 QuartzCore
    【解决方案2】:

    如果您在滚动视图后面有纯色背景,则只需在滚动视图顶部覆盖图像而不是尝试在其中执行蒙版,您将获得更好的性能。

    【讨论】:

    • 是的,我正在考虑这个问题。不幸的是,在这种情况下,我需要一张图片作为背景,而且背景图片也必须是动态的。
    【解决方案3】:

    尝试以下方法:

    // I assume you are in a UIViewController and self.view is set to some kind of view
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 420)];
    scrollView.backgroundColor = [UIColor redColor];
    [self.view addSubview: scrollView];
    [scrollView release];
    
    // add img with gradient
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"my-gradient.png"];
    imgView.frame = CGRectMake(0, 0, 160, 420);
    [self.view addSubview: imgView];
    [imgView release];
    

    假设“my-gradient.png”是实际包含渐变的图像,这将为您提供从左侧开始一直到中心的整个高度的渐变。

    【讨论】:

      【解决方案4】:

      这类操作是资源消耗大户。最好的方法是(如果你的情况允许的话)在你的 UIScrollView 上放置一个掩码图像。此图像的背景应该是透明的(例如 png32),并且图像应该是 alpha 渐变。

      【讨论】:

        【解决方案5】:

        使用 insertView:yourView atIndex:0

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-16
          • 2021-07-30
          • 1970-01-01
          • 2012-03-07
          • 1970-01-01
          • 2012-01-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多