简体   繁体   中英

Change Background color of UIView With Multicolor

i want to make my UIView Background color like following image

在此处输入图像描述

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.

1.Create a CAGradientLayer.

2.Set the layer's colours property to your rainbow colours.

3.set startPoint and the layer's endPoint as per your requirement.

4.Create a CAShapeLayer(for the shape) and set it as the gradient layer's mask.

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.thinkandbuild.it/playing-around-with-core-graphics-core-animation-and-touch-events-part-1/

Step 1: Create an ENUM (for horizontal and vertical selection)

Step 2: Create an extension of UIView and apply it in any 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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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