简体   繁体   English

UIView 上的渐变蒙版

[英]Gradient mask on UIView

I have a UIView and want to have the bottom part of it fade out to 0 opacity.我有一个 UIView 并且希望它的底部淡出到 0 不透明度。

May this be done to a UIView (CALayer) in order to affect an entire UIView and its content?是否可以对 UIView (CALayer) 执行此操作以影响整个 UIView 及其内容?

Yes, you can do that by setting CAGradientLayer as your view's layer mask:是的,您可以通过将CAGradientLayer设置为视图的图层蒙版来做到这一点:

#import <QuartzCore/QuartzCore.h>

...

CAGradientLayer *maskLayer = [CAGradientLayer layer];

maskLayer.frame = view.bounds;
maskLayer.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor];
maskLayer.startPoint = CGPointMake(0.5, 0);
maskLayer.endPoint = CGPointMake(0.5, 1.0);

view.layer.mask = maskLayer;

PS You also need to link QuartzCore.framework to your app to make things work. PS 您还需要将QuartzCore.framework链接到您的应用程序以使其正常工作。

Using an Image as the mask to prevent Layout issues.使用图像作为掩码来防止布局问题。

Although Vladimir's answer is correct, the issue is to sync the gradient layer after view changes.尽管 Vladimir 的回答是正确的,但问题是在视图更改后同步渐变层。 For example when you rotate the phone or resizing the view.例如,当您旋转手机或调整视图大小时。 So instead of a layer, you can use an image for that:因此,您可以使用图像代替图层:

@IBDesignable
class MaskableLabel: UILabel {
    var maskImageView = UIImageView()

    @IBInspectable
    var maskImage: UIImage? {
        didSet {
            maskImageView.image = maskImage
            updateView()
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        updateView()
    }

    func updateView() {
        if maskImageView.image != nil {
            maskImageView.frame = bounds
            mask = maskImageView
        }
    }
}

Then with a simple gradient mask like this , You can see it even right in the storyboard.然后使用像这样的简单渐变蒙版,您甚至可以在故事板中看到它。

预习

Note:笔记:

You can use this class and replace UILabel with any other view you like to subclass.你可以使用这个class和替换UILabel与你喜欢的子类的任何其他视图。

🎁 Bones: 🎁 骨骼:

You can use any other shaped image as the mask just like that.您可以像这样使用任何其他形状的图像作为蒙版。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM