使用UIBezierPath在Swift 3.x中绘制一条直线

3
我将尝试在UIView上使用UIBezierpath绘制一条线。我认为我遗漏了某些内容,但是无法找到它。
这是我的代码:
// Code for touch recognition
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false
    if let touch = touches.first as? UITouch? {
        lastPoint = (touch?.location(in: fullview))!
        //print(lastPoint)
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = true
    if let touch = touches.first as? UITouch? {
        let currentPoint = touch?.location(in: fullview)
        drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint!)

        lastPoint = currentPoint!
        //print(lastPoint)
        //print("touch moved")
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if !swiped {
        drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
    }
    //print("touch ended")
}

//code for drawing
func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint){

    UIGraphicsBeginImageContext(fullview.frame.size)

    let context = UIGraphicsGetCurrentContext()

    let aPath = UIBezierPath()

    //aPath.move(to: fromPoint)
    //aPath.addLine(to: toPoint)
    aPath.lineWidth=10.0
    aPath.lineJoinStyle = .round
    aPath.move(to: CGPoint(x:15,y:15))
    aPath.addLine(to: CGPoint(x:80,y:80))
    aPath.addClip()
    aPath.close()
    UIColor.green.set()
    aPath.stroke()

    //print("drawline")
    //print("Frompoint = ",fromPoint)
    //print("topoint = ",toPoint)

  /*  context?.setLineCap(.round)
    context?.setLineWidth(brushWidth)
    context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
    context?.setBlendMode(.normal)

    context?.beginPath()
    context?.move(to: fromPoint)
    context?.addLine(to: toPoint)
    context?.closePath()
    context?.strokePath()*/


    //let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    fullview.setNeedsDisplay()
}

正如您所看到的,我也尝试使用上下文进行翻译,但效果并不理想。


谷歌是我的好朋友 :) 我只是用了错误的关键词,谢谢。 - Tristan G
这实际上就是你的确切职称 :-) - shallowThought
2个回答

11

我用这个来画一条线:

    let doYourPath = UIBezierPath(rect: CGRect(x: xPos, y: yPos, width: yourWidth, height: yourHeight))
    let layer = CAShapeLayer()
    layer.path = doYourPath.cgPath
    layer.strokeColor = UIColor.white.cgColor
    layer.fillColor = UIColor.white.cgColor

    self.view.layer.addSublayer(layer)

希望这能对你有所帮助。这只是在Swift中绘制一条直线的一种方式。


3

嗯,您正在绘制到图像上下文(离屏位图),而不是视图中。这很可能不是您想要的?请确保您已经阅读了iOS绘图概念

您的UIView子类应该只跟踪触摸位置(比如一个var touchedPositions = [CGPoint]())并调用setNeedsDisplay()。 然后在您的子类中实现func draw(_ rect: CGRect)方法。在此方法中,根据您跟踪的位置创建路径并进行绘制(无需创建新的上下文)。


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