简体   繁体   English

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

[英]Change Background color of UIView With Multicolor

i want to make my UIView Background color like following image我想让我的 UIView 背景颜色如下图

在此处输入图像描述

when i press on button the view's background color will become like above.当我按下按钮时,视图的背景颜色将变为如上。 i was googling to much but not find a way.Can you please help me?我在谷歌上搜索了很多但找不到方法。你能帮帮我吗?

You can do this using CALayer. 您可以使用CALayer进行此操作。

1.Create a CAGradientLayer. 1.创建一个CAGradientLayer。

2.Set the layer's colours property to your rainbow colours. 2.将图层的颜色属性设置为彩虹色。

3.set startPoint and the layer's endPoint as per your requirement. 3.根据需要设置startPoint和图层的endPoint。

4.Create a CAShapeLayer(for the shape) and set it as the gradient layer's mask. 4.创建一个CAShapeLayer(用于形状)并将其设置为渐变层的蒙版。

Enjoy!! 请享用!!

To draw something like that you need to use core graphic. 要绘制类似的图片,您需要使用核心图形。 Core graphics provides gradient feature that can be use. 核心图形提供了可以使用的渐变功能。

Links: http://www.raywenderlich.com/32925/core-graphics-tutorial-shadows-and-gloss 链接: 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/ http://www.thinkandbuild.it/playing-around-with-core-graphics-core-animation-and-touch-events-part-1/

Step 1: Create an ENUM (for horizontal and vertical selection)第 1 步:创建一个 ENUM(用于水平和垂直选择)

Step 2: Create an extension of UIView and apply it in any uiView.第二步:创建UIView的分机,并应用到任意uiView中。

Example:例子:

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)
      }
}

Usage:用法:

let gradientView: UIView
gradientView.createGradient()

在此处输入图像描述

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

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