2017-10-18 7 views
4

구성 요소에 그라디언트를 추가했는데, 기울기가 있습니다. 이 그래디언트는 그래디언트 벡터에 수직이 아닙니다. 장치 iPhone 6s는 편의상 크기를 일정하게 설정했습니다. 무엇이 문제 일 수 있습니까?iOS 기울기가 그래디언트 벡터에 수직이 아닙니다.

class ViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let topPoint = CGPoint(x: 33, y: -55) 
    let botPoint = CGPoint(x: 217, y: 469) 

    let iPhoneSize = CGSize(width: 375, height: 667) 

    let additionalLayer = CAGradientLayer() 
    additionalLayer.frame = view.bounds 

    additionalLayer.startPoint = CGPoint(x: topPoint.x/iPhoneSize.width, y: topPoint.y/iPhoneSize.height) 
    additionalLayer.endPoint = CGPoint(x: botPoint.x/iPhoneSize.width, y: botPoint.y/iPhoneSize.height) 
    additionalLayer.colors = [UIColor.white.cgColor, UIColor.darkGray.cgColor, UIColor.black.cgColor] 
    additionalLayer.locations = [0.0, 0.468, 1.0] 
    drawLine(onLayer: additionalLayer, fromPoint: topPoint, toPoint: botPoint) 
    view.layer.addSublayer(additionalLayer) 
} 

func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end: CGPoint) { 
    let line = CAShapeLayer() 
    let linePath = UIBezierPath() 
    linePath.move(to: start) 
    linePath.addLine(to: end) 
    line.path = linePath.cgPath 
    line.fillColor = nil 
    line.opacity = 1.0 
    line.strokeColor = UIColor.red.cgColor 
    layer.addSublayer(line) 
} 

}

P.S. 나는이 코드를 viewDidLayoutSubviews()에 추가하려고 시도했다.

P.P.S. 또한 스크린 샷을 추가했습니다.

enter image description here

+0

으악는 ... 내 대답이 잘못되었습니다. 다음은 귀하가 찾고있는 것입니다 (https://stackoverflow.com/a/43176174/6257435). – DonMag

답변

0

대신 CAGradientLayer의 사용 drawLinearGradient.

아래 빠른 솔루션의 예 :

override func viewDidLoad() { 
     super.viewDidLoad() 

     let topPoint = CGPoint(x: 33, y: -55) 
     let botPoint = CGPoint(x: 217, y: 469) 

     let additionalLayer = CALayer() 
     additionalLayer.frame = view.bounds 

     UIGraphicsBeginImageContext(view.bounds.size) 
     if let context = UIGraphicsGetCurrentContext() { 
      let colorSpace = CGColorSpaceCreateDeviceRGB() 
      let colors : [CGFloat] = [1.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 0.0, 1.0] 
      let locations : [CGFloat] = [0.0, 0.468, 1.0] 
      let gradient = CGGradient(colorSpace: colorSpace, colorComponents: colors, locations: locations, count: 3) 
      context.drawLinearGradient(gradient!, start: topPoint, end: botPoint, options: CGGradientDrawingOptions.drawsAfterEndLocation) 
      additionalLayer.contents = context.makeImage()! 
     } 
     drawLine(onLayer: additionalLayer, fromPoint: topPoint, toPoint: botPoint) 
     view.layer.addSublayer(additionalLayer) 
    } 

Screenshot with result

관련 문제