CAGradientLayer diagonal gradient

前端 未结 3 1725
遥遥无期
遥遥无期 2020-12-12 18:42

I use the following CAGradientLayer:

let layer = CAGradientLayer()
layer.colors = [
    UIColor.redColor().CGColor,
    UIColor.greenColor().CGColor         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 19:12

    Here's the math to fix the endPoint

    let width = bounds.width
    let height = bounds.height
    let dx = endPoint.x - startPoint.x
    let dy = endPoint.y - startPoint.y
    if width == 0 || height == 0 || width == height || dx == 0 || dy == 0 {
      return
    }
    let ux = dx * width / height
    let uy = dy * height / width
    let coef = (dx * ux + dy * uy) / (ux * ux + uy * uy)
    endPoint = CGPoint(x: startPoint.x + coef * ux, y: startPoint.y + coef * uy)
    

提交回复
热议问题