首页 文章

UIView透明渐变

提问于
浏览
34

鉴于iOS上的任意UIView,是否有一种方法可以使用Core Graphics(CAGradientLayer)来应用“前景透明”渐变?

我不能使用标准的CAGradientLayer,因为背景比UIColor更复杂 . 我也无法覆盖PNG,因为背景会随着我的子视图沿其父垂直滚动视图滚动而改变(见图) .

我有一个非优雅的后备:让我的uiview剪辑其子视图,并在滚动父滚动视图时移动背景的预渲染渐变png .

transparent uiview gradient problem

5 回答

  • 6

    这是一个令人尴尬的简单修复:应用CAGradientLayer作为我的子视图的掩码 .

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = _fileTypeScrollView.bounds;
    gradientLayer.colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor, nil];
    gradientLayer.startPoint = CGPointMake(0.8f, 1.0f);
    gradientLayer.endPoint = CGPointMake(1.0f, 1.0f);
    _fileTypeScrollView.layer.mask = gradientLayer;
    

    感谢Cocoanetics指出我正确的方向!

  • 94

    这就是我要做的 .

    Step 1 定义自定义渐变视图(Swift 4):

    import UIKit
    
    class GradientView: UIView {
        override open class var layerClass: AnyClass {
            return CAGradientLayer.classForCoder()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            let gradientLayer = self.layer as! CAGradientLayer
            gradientLayer.colors = [
                UIColor.white.cgColor,
                UIColor.init(white: 1, alpha: 0).cgColor
            ]
            backgroundColor = UIColor.clear
        }
    }
    

    Step 2 - 在故事板中拖放 UIView 并将其自定义类设置为 GradientView

    enter image description here

    举个例子,这就是上面的渐变视图的样子:


    https://github.com/yzhong52/GradientViewDemo

  • 0

    Gradient Example

    我刚刚遇到了同样的问题,结束了写自己的课程 . 这似乎是严重的矫枉过正,但这是我能找到做透明渐变的唯一方法 . 你可以看到我的writeup and code example here

    它基本上归结为一个创建两个图像的自定义UIView . 一种是纯色,另一种是用作图像蒙版的渐变 . 从那里我将生成的图像应用到uiview.layer.content .

    乔,我希望它有所帮助

  • 2

    我不想这么说,但我认为你进入了CUSTOM UIView的土地 . 我想我会尝试在覆盖drawRect例程的自定义UIView中实现它 .

    有了这个,您可以拥有该视图,放置在实际滚动视图的顶部,并使您的渐变视图(如果您愿意)“传递”所有触摸事件(即放弃第一响应者) .

  • 0

    我使用了上面接受的(OP)答案并遇到了an upvoted comment中提到的相同问题 - 当视图滚动时,从屏幕开始的所有内容现在都是透明的,由掩码覆盖 .

    解决方案是使用文本视图添加渐变图层作为 superview 的蒙版,而不是 scroll view 's mask. In my case, I' m,文本视图包含在名为 contentView 的视图中 .

    我添加了第三种颜色并使用了 locations 而不是 startPointendPoint ,因此文本视图下方的项目仍然可见 .

    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.contentView!.bounds
    gradientLayer.colors = [UIColor.white.cgColor, UIColor.clear.cgColor, UIColor.white.cgColor]
    
    // choose position for gradient, aligned to bottom of text view
    let bottomOffset = (self.textView!.frame.size.height + self.textView!.frame.origin.y + 5)/self.contentView!.bounds.size.height
    let topOffset = bottomOffset - 0.1
    let bottomCoordinate = NSNumber(value: Double(bottomOffset))
    let topCoordinate = NSNumber(value: Double(topOffset))
    gradientLayer.locations = [topCoordinate, bottomCoordinate, bottomCoordinate]
    
    self.contentView!.layer.mask = gradientLayer
    

    之前,从屏幕外开始的文本永久不可见 . 通过我的修改,滚动按预期工作,并且掩码不覆盖“关闭”按钮 .

    screenshot

相关问题