用UIBezierPath画一条线

时间:2014-10-30 20:12:30

标签: ios swift uibezierpath

首次使用BezierPaths,想知道这个函数实际上应该如何实现。目前贝塞尔曲线路径在图像的帧内移动,而不是在屏幕上绘图。

有更好的方法吗?

func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {

    var maxWidth = abs(start.x - end.x)
    var maxHeight = abs(start.y - end.y)

    var contextSize : CGSize!
    if maxWidth == 0 {
        contextSize = CGSize(width: 1, height: maxHeight)
    }else {
        contextSize = CGSize(width: maxWidth, height: 1)
    }

    //design the path
    UIGraphicsBeginImageContextWithOptions(contextSize, false, 0)
    var path = UIBezierPath()
    path.lineWidth = 1.0
    lineColor.set()

    //draw the path and make visible
    path.moveToPoint(start)
    path.addLineToPoint(end)
    path.stroke()

    //create image from path and add to subview
    var image = UIGraphicsGetImageFromCurrentImageContext()
    var imageView = UIImageView(image: image)
    view.addSubview(imageView)
    UIGraphicsEndImageContext()
}

3 个答案:

答案 0 :(得分:53)

结束这样做:

func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {

    //design the path
    var path = UIBezierPath()
    path.moveToPoint(start)
    path.addLineToPoint(end)

    //design path in layer
    var shapeLayer = CAShapeLayer()
    shapeLayer.path = path.CGPath
    shapeLayer.strokeColor = lineColor.CGColor
    shapeLayer.lineWidth = 1.0

    view.layer.addSublayer(shapeLayer)
}

答案 1 :(得分:7)

Swift 3.1版本的William Falcon的回答+改进

这只是已经接受的答案的更新版本,我只是添加了一点。

func drawLineFromPointToPoint(startX: Int, toEndingX endX: Int, startingY startY: Int, toEndingY endY: Int, ofColor lineColor: UIColor, widthOfLine lineWidth: CGFloat, inView view: UIView) {

    let path = UIBezierPath()
    path.move(to: CGPoint(x: startX, y: startY))
    path.addLine(to: CGPoint(x: endX, y: endY))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = lineColor.cgColor
    shapeLayer.lineWidth = lineWidth

    view.layer.addSublayer(shapeLayer)

}

当然,实施将是

drawLineFromPointToPoint(startX: Int, toEndingX: Int, startingY: Int, toEndingY: Int, ofColor: UIColor, widthOfLine: CGFloat, inView: UIView)

我从接受的答案中更改了

我将vars更改为let,并且更容易输入x和y的开头和结尾。我还允许用户更改线条的宽度。

我选择的值为Int类型,但您可以将其更改为其他允许的选项。

答案 2 :(得分:4)

Swift 4

func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {

    //design the path
    let path = UIBezierPath()
    path.move(to: start)
    path.addLine(to: end)

    //design path in layer
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = lineColor.cgColor
    shapeLayer.lineWidth = 1.0

    view.layer.addSublayer(shapeLayer)
}