create a view with a gauge that changes background colour from light blue to dark blue in swift

To create a view with a gauge that changes background color from light blue to dark blue in Swift, you can use the following steps:

  1. Create a UIView with the desired dimensions and add it to your parent view.
main.swift
let gaugeView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.addSubview(gaugeView)
102 chars
3 lines
  1. Create a CAShapeLayer with a circular path that represents the gauge.
main.swift
let shapeLayer = CAShapeLayer()
let centerPoint = CGPoint(x: gaugeView.bounds.midX, y: gaugeView.bounds.midY)
let radius = min(gaugeView.bounds.width, gaugeView.bounds.height) / 2 - 10
let startAngle = -CGFloat.pi / 2
let endAngle = startAngle + 2 * CGFloat.pi

let path = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 16
shapeLayer.fillColor = UIColor.clear.cgColor
gaugeView.layer.addSublayer(shapeLayer)
574 chars
13 lines
  1. Add a CAGradientLayer as a mask to the CAShapeLayer to create the gauge effect.
main.swift
let gradientLayer = CAGradientLayer()
gradientLayer.frame = gaugeView.bounds
gradientLayer.colors = [UIColor.lightBlue.cgColor, UIColor.darkBlue.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)

let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
maskLayer.fillColor = UIColor.black.cgColor
maskLayer.strokeColor = UIColor.clear.cgColor
gradientLayer.mask = maskLayer

gaugeView.layer.addSublayer(gradientLayer)
476 chars
14 lines
  1. Animate the gradient layer from the light blue color to the dark blue color.
main.swift
let colorAnimation = CABasicAnimation(keyPath: "colors")
colorAnimation.fromValue = [UIColor.lightBlue.cgColor, UIColor.darkBlue.cgColor]
colorAnimation.toValue = [UIColor.darkBlue.cgColor, UIColor.darkBlue.cgColor]
colorAnimation.duration = 3.0
gradientLayer.add(colorAnimation, forKey: "colorAnimation")
306 chars
6 lines

With these steps, you have created a view with a gauge that changes background color from light blue to dark blue in Swift.

gistlibby LogSnag