IOS Gradient not perpendicular to the gradient vector

I added a gradient on the component, it is at an angle. This gradient is not perpendicular to the gradient vector. The iPhone 6s has been set to a constant size for convenience. What could be the problem?

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)
}

}

PS I tried adding this code to viewDidLayoutSubviews ()

PPS A screenshot is also added.

enter image description here

+4
source share
1 answer

Use drawLinearGradient instead of CAGradientLayer.

An example of a quick fix below:

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 of the result

0
source

Source: https://habr.com/ru/post/1687719/


All Articles