我试图在带有UIBezierpath的UIView上画一条线。我想我缺少了一些东西,但是找不到。

这是我的代码:

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

如您所见,我也在上下文中进行了尝试,但是它也不起作用。

最佳答案

我用它来画一条线:

    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)

希望这对您有所帮助。这只是快速画线的一种方法。

10-08 16:39