如何防止一次绘制多条线(快速)?

时间:2019-03-30 04:37:55

标签: ios swift

当我慢慢画一条线时,我相信它会检测到它是多条线而不是一条线,因此它会使该线变深。

我正在关注本教程https://www.raywenderlich.com/5895-uikit-drawing-tutorial-how-to-make-a-simple-drawing-app

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

    func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
        //1
        UIGraphicsBeginImageContext(view.frame.size)
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
        tempImageView.image?.draw(in: view.bounds)

        //2
        context.move(to: fromPoint)
        context.addLine(to: toPoint)

        //3
        context.setLineCap(.round)
        context.setBlendMode(.normal)
        context.setLineWidth(brushWidth)
        context.setStrokeColor(color.cgColor)
        context.setStrokeColor(UIColor(red: red,
                                       green: green,
                                       blue: blue,
                                       alpha: opacity).cgColor)

        //4
        context.strokePath()

        //5
        tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        tempImageView.alpha = opacity
        UIGraphicsEndImageContext()
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
        }
        //6
        swiped = true
        let currentPoint = touch.location(in: view)
        drawLine(from: lastPoint, to: currentPoint)

        //7
        lastPoint = currentPoint
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !swiped {
            //draw a single point
            drawLine(from: lastPoint, to: lastPoint)
        }
        //merge tempImageView into mainImageView
        UIGraphicsBeginImageContext(mainImageView.frame.size)
        mainImageView.image?.draw(in: view.bounds, blendMode: .normal, alpha: 1.0)
        tempImageView?.image?.draw(in: view.bounds, blendMode: .normal, alpha: opacity)
        mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        tempImageView.image = nil
    }

当我绘制它时,很难看到它使它们相交的点变暗。我希望它更加引人注目。在这张照片中,不透明度设置为0.5。

enter image description here

线条上有点的区域是我绘制得很快的地方。牢固的地方是我慢慢画线的地方。我希望所有线条看起来都像快速绘制的线条-当然要减去点。

1 个答案:

答案 0 :(得分:0)

您可以将绘制线上下文的混合模式更改为.copy,以获得相同的颜色

来自

    //3
    context.setBlendMode(.normal)

    //3
    context.setBlendMode(.copy)