ios - 使用 UIBezierPath 在 Swift 3.x 中画一条线

标签 ios swift xcode uiview drawing

我正在尝试使用 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)

希望对您有所帮助。这只是在 swift 中画线的一种方法。

关于ios - 使用 UIBezierPath 在 Swift 3.x 中画一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41167016/

相关文章:

objective-c - 如何在没有 IB 的情况下添加调整大小

iOS 6 社交框架 Facebook 与图形 api 未发布

ios - 绘制圆线iOS Swift

swift - 如何访问枚举之外的属性

ios - Xcode Swift - 修改 subview 属性

c - Xcode 链接器错误(重复符号),而 gcc 工作正常

ios - 避免将对象重复保存到 Realm 的正确方法是什么?

ios - 将数据从 tableview controller 传递到 view controller,但它显示为 null

swift - 平铺背景图像

ios - 单元格标签无法捕获表格 View 中的值