Skip to content

Instantly share code, notes, and snippets.

@gtmsakhiya
Last active September 1, 2023 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtmsakhiya/f9708e787846eace5f48bd27c008393d to your computer and use it in GitHub Desktop.
Save gtmsakhiya/f9708e787846eace5f48bd27c008393d to your computer and use it in GitHub Desktop.
gradient color set in view using swift
// Created by Gautam Sakhiya 27/08/23.
// Set view gradient color
public func gradientColor(yourView:UIView, startColor: UIColor, endColor: UIColor, colorAngle: CGFloat){
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
gradientLayer.locations = [0.0, 1.0]
let (start, end) = gradientPointsForAngle(colorAngle)
gradientLayer.startPoint = start
gradientLayer.endPoint = end
gradientLayer.frame = yourView.bounds
yourView.layer.insertSublayer(gradientLayer, at: 0)
yourView.layer.masksToBounds = true
}
private func gradientPointsForAngle(_ angle: CGFloat) -> (CGPoint, CGPoint) {
let end = pointForAngle(angle)
let start = oppositePoint(end)
let p0 = transformToGradientSpace(start)
let p1 = transformToGradientSpace(end)
return (p0, p1)
}
private func pointForAngle(_ angle: CGFloat) -> CGPoint {
let radians = angle * .pi / 180.0
var x = cos(radians)
var y = sin(radians)
if (abs(x) > abs(y)) {
x = x > 0 ? 1 : -1
y = x * tan(radians)
} else {
y = y > 0 ? 1 : -1
x = y / tan(radians)
}
return CGPoint(x: x, y: y)
}
private func oppositePoint(_ point: CGPoint) -> CGPoint {
return CGPoint(x: -point.x, y: -point.y)
}
private func transformToGradientSpace(_ point: CGPoint) -> CGPoint {
return CGPoint(x: (point.x + 1) * 0.5, y: 1.0 - (point.y + 1) * 0.5)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment