小编典典

用UIBezierPath画一条线

swift

第一次使用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()
}

阅读 304

收藏
2020-07-07

共1个答案

小编典典

最终这样做:

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