繁体   English   中英

使用多色更改 UIView 的背景颜色

[英]Change Background color of UIView With Multicolor

我想让我的 UIView 背景颜色如下图

在此处输入图像描述

当我按下按钮时,视图的背景颜色将变为如上。 我在谷歌上搜索了很多但找不到方法。你能帮帮我吗?

您可以使用CALayer进行此操作。

1.创建一个CAGradientLayer。

2.将图层的颜色属性设置为彩虹色。

3.根据需要设置startPoint和图层的endPoint。

4.创建一个CAShapeLayer(用于形状)并将其设置为渐变层的蒙版。

请享用!!

要绘制类似的图片,您需要使用核心图形。 核心图形提供了可以使用的渐变功能。

链接: http//www.raywenderlich.com/32925/core-graphics-tutorial-shadows-and-gloss

http://www.thinkandbuild.it/playing-around-with-core-graphics-core-animation-and-touch-events-part-1/

第 1 步:创建一个 ENUM(用于水平和垂直选择)

第二步:创建UIView的分机,并应用到任意uiView中。

例子:

enum GradientColorDirection
{
    case vertical
    case horizontal
}
extension UIView {

func createGradient(opacity: Float = 1, direction: GradientColorDirection = .vertical)
    {
        let colors: [UIColor] = [UIColor.red,
                                   UIColor.yellow,
                                   UIColor.green,
                                   UIColor.systemBlue,
                                   UIColor.blue,
                                   UIColor.systemPink,
                                   UIColor.red]
                  
          let gradientLayer = CAGradientLayer()
          gradientLayer.opacity = opacity
          gradientLayer.colors = colors.map { $0.cgColor }

          if case .horizontal = direction {
              gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
              gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
          }

          gradientLayer.bounds = self.bounds
          gradientLayer.anchorPoint = CGPoint.zero
          self.layer.addSublayer(gradientLayer)
      }
}

用法:

let gradientView: UIView
gradientView.createGradient()

在此处输入图像描述

暂无
暂无

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

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