Swift 3中UIView的bezierPath,只需要曲线。

8
当我在UIView上使用Swift绘制贝塞尔路径时,会出现一条直线。我只需要曲线,请问是否可以去掉这条直线。
我可以通过以下方法移除灰色填充: line.fillColor = UIColor.clear.cgColor 不确定如何去掉这条直线。

enter image description here

代码:

    let line = CAShapeLayer()
    let linePath = UIBezierPath()
    linePath.move(to: start)
    linePath.addLine(to: end)
    var dis = (end.x - start.x)/3.0
    linePath.addCurve(to: start,
                  controlPoint1: CGPoint(x: start.x + dis, y: start.y + dis),
                  controlPoint2: CGPoint(x: end.x - dis, y: end.y - dis))

    line.path = linePath.cgPath
    line.strokeColor = UIColor.red.cgColor
    //line.fillColor = UIColor.clear.cgColor
    line.lineWidth = 4.0
    line.opacity = 0.6
    self.view.layer.addSublayer(line)
2个回答

4
请尝试以下代码。指定起点和终点,并使用三角函数的pi来表示圆曲线。如果您想使用这些进行动画,请将以下代码添加到UIView中。

Example image

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let pi = CGFloat(Float.pi)
        let start:CGFloat = 0.0
        let end :CGFloat = pi
        
        // circlecurve
        let path: UIBezierPath = UIBezierPath();
        path.addArc(
            withCenter: CGPoint(x:self.view.frame.width/4, y:self.view.frame.height/4),
            radius: 300,
            startAngle: start,
            endAngle: end,
            clockwise: true
        )
        let layer = CAShapeLayer()
        layer.fillColor = UIColor.clear.cgColor
        layer.strokeColor = UIColor.orange.cgColor
        layer.path = path.cgPath
        self.view.layer.addSublayer(layer)   
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

4
不要关闭路径。当您关闭贝塞尔曲线路径时,会在路径的开始和结束之间添加一条直线。如果您不关闭路径,则不应该这样做。(但是,您无法填充非闭合路径,只能描边它。)
如果这没有帮助您,您需要编辑您的问题以显示创建和绘制路径的代码。

嗨,@Duncan,我已经更新了代码。即使删除了close,它仍然会画直线。 - user320478
你的代码有一个明确的命令,从起点到终点画一条直线:linePath.addLine(to: end)。但它被写成从终点到起点画曲线。去掉addLine命令,先移动到终点,然后调用添加从终点到起点的曲线(或移动到曲线的起始点,然后重写你的linePath.addCurve以添加从起始点到结束点的曲线)。 - Duncan C

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接