Swift 3在同一个UIView中放了2种颜色

Boa*_*nut 0 uiview uiimageview ios swift

我想在UIViews和UIImageViews上实现这个效果:

的UIImageView

的UIView

在UIView上,我知道我可以用不同的颜色在其中放置2,但我认为必须有更好的方法,我不知道如何在UIImageVIew中做到这一点.某种pod会非常有用,因为我找不到它.

Au *_*Ris 5

您可以添加一个渐变图层,而不是从一种颜色转换到另一种颜色,而是从一种颜色转换为相同颜色直到中间点,并且与后半部分相同.检查示例:

let twoColorView = UIView(frame: CGRect(x: 40, y: 100, width: 200, height: 100))
let gradientLayer = CAGradientLayer()
gradientLayer.frame = twoColorView.bounds
gradientLayer.colors = [UIColor.red.cgColor, UIColor.red.cgColor, UIColor.blue.cgColor, UIColor.blue.cgColor]
gradientLayer.locations = [NSNumber(value: 0.0), NSNumber(value: 0.5), NSNumber(value: 0.5), NSNumber(value: 1.0)]
twoColorView.layer.addSublayer(gradientLayer)
Run Code Online (Sandbox Code Playgroud)

当然,您可以进一步设计该视图,例如:

twoColorView.layer.cornerRadius = twoColorView.bounds.height / 2
twoColorView.layer.masksToBounds = true
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述

编辑:

它可以推广为接受任意数量的颜色.创建UIView扩展并在那里添加逻辑.通过这种方式,颜色可以应用于任何UIView及其子类,例如UILabel,UIButton,UIImageView等.

extension UIView {
    func addColors(colors: [UIColor]) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.bounds

        var colorsArray: [CGColor] = []
        var locationsArray: [NSNumber] = []
        for (index, color) in colors.enumerated() {
            // append same color twice
            colorsArray.append(color.cgColor)
            colorsArray.append(color.cgColor)
            locationsArray.append(NSNumber(value: (1.0 / Double(colors.count)) * Double(index)))
            locationsArray.append(NSNumber(value: (1.0 / Double(colors.count)) * Double(index + 1)))
        }

        gradientLayer.colors = colorsArray
        gradientLayer.locations = locationsArray

        self.backgroundColor = .clear
        self.layer.addSublayer(gradientLayer)

        // This can be done outside of this funciton
        self.layer.cornerRadius = self.bounds.height / 2
        self.layer.masksToBounds = true
    }
}
Run Code Online (Sandbox Code Playgroud)

并添加颜色:

    let colorView = UIImageView(frame: CGRect(x: 40, y: 100, width: 200, height: 100))
    colorView.addColors(colors: [.red, .green, .blue])
    view.addSubview(colorView)
Run Code Online (Sandbox Code Playgroud)

这是结果:

在此输入图像描述

注意不要在视图的生命周期中多次调用此函数,因为它会将子图层添加到彼此之上.因此,在addColors再次呼叫之前,请先调用一次或删除子层.所以当然还有改进的余地.