小编典典

使用Swift 3.0实时绘制线条

swift

我正在尝试在UIImageView上绘制。使用Swift 1.2,我能够使其工作,但是我不得不将其转换为swift 3.0,而我却无法使其工作。

它需要做的就是用手指在屏幕上绘制出精确的图画。

该代码没有错误,但是什么也不显示。

变量;

var lastPoint = CGPoint.zero
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false

代码;

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false
    if let touch = touches.first {
        lastPoint = touch.location(in: self.view)
    }
}

func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {


    imageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
    UIGraphicsBeginImageContext(self.imageView.bounds.size);
    let context = UIGraphicsGetCurrentContext()

        context?.move(to: fromPoint)
        context?.addLine(to: toPoint)

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

        imageView.image = UIGraphicsGetImageFromCurrentImageContext()
        imageView.alpha = opacity
        UIGraphicsEndImageContext()

}

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

        lastPoint = currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if !swiped {
                    // draw a single point
        self.drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
    }

阅读 663

收藏
2020-07-07

共1个答案

小编典典

您必须开始图像上下文:

UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)

您还必须摸索路径:

context?.strokePath()

您也没有绘制上一张图像:

imageView.image?.draw(in: view.bounds)

从而:

func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)

    imageView.image?.draw(in: view.bounds)

    let context = UIGraphicsGetCurrentContext()

    context?.move(to: fromPoint)
    context?.addLine(to: toPoint)

    context?.setLineCap(CGLineCap.round)
    context?.setLineWidth(brushWidth)
    context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
    context?.setBlendMode(CGBlendMode.normal)
    context?.strokePath()

    imageView.image = UIGraphicsGetImageFromCurrentImageContext()
    imageView.alpha = opacity
    UIGraphicsEndImageContext()
}
2020-07-07