Skip to content

Instantly share code, notes, and snippets.

@JayachandraA
Created December 27, 2018 10:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JayachandraA/1248545d4d8d8556a4b1ea1bbd729180 to your computer and use it in GitHub Desktop.
Save JayachandraA/1248545d4d8d8556a4b1ea1bbd729180 to your computer and use it in GitHub Desktop.
gradient layer with angle in swift
// how to create a gradient view
let gradientLayer = CAGradientLayer()
gradientLayer.frame = view.bounds
gradientLayer.colors = [UIColor.orange.cgColor, UIColor.white.cgColor,UIColor.green.cgColor]
gradientLayer.locations = [0.0, 0.5, 1.0]
gradientLayer.apply(angle: 45.0)
view.layer.insertSublayer(gradientLayer, at: 0)
//helper extention to CAGradientLayer
extension CAGradientLayer {
func apply(angle : Double) {
let x: Double! = angle / 360.0
let a = pow(sinf(Float(2.0 * Double.pi * ((x + 0.75) / 2.0))),2.0);
let b = pow(sinf(Float(2*Double.pi*((x+0.0)/2))),2);
let c = pow(sinf(Float(2*Double.pi*((x+0.25)/2))),2);
let d = pow(sinf(Float(2*Double.pi*((x+0.5)/2))),2);
endPoint = CGPoint(x: CGFloat(c),y: CGFloat(d))
startPoint = CGPoint(x: CGFloat(a),y:CGFloat(b))
}
}
@CodeSurgeonX
Copy link

Hi it would be really great if you could please share the logic behind the calculations, I am unable to understand why you did what you did, so if could you guide on the calculation bit it would be really really appreciated

@thezonie
Copy link

The code above causes Xcode 13.4 to take around a minute to build for some reason, possibly due to the type inference / type conversion. The following simplified code instead takes around 2 seconds to build:

func apply(angle: CGFloat) {
    let x = angle / 360

    let a = pow(sin(.pi * (x + 0.75)), 2)
    let b = pow(sin(.pi * (x + 0.0)), 2)
    let c = pow(sin(.pi * (x + 0.25)), 2)
    let d = pow(sin(.pi * (x + 0.5)), 2)

    endPoint = CGPoint(x: c, y: d)
    startPoint = CGPoint(x: a, y: b)
}

@JayachandraA
Copy link
Author

@thezonie Yeah, that's great. Thanks for the update. 💕

@msnazarow
Copy link

msnazarow commented Jan 9, 2023

func getPoints(from degrees: Double) -> (UnitPoint, UnitPoint) {
let x = (180 - degrees) / 360

let x0 = pow(sin(.pi * (x + 0.75)), 2)
let y0 = pow(sin(.pi * (x + 0.0)), 2)
let x1 = pow(sin(.pi * (x + 0.25)), 2)
let y1 = pow(sin(.pi * (x + 0.5)), 2)

return (.init(x: x0, y: y0), .init(x: x1, y: y1))

}

works for me when copy angle from figma

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment