在iOS / swift3中的view / imageview上绘制一条线

时间:2016-11-13 13:38:05

标签: ios swift drawing swift3 cgpoint

我发现了一个类似于我自己的问题: Draw a line realtime with Swift 3.0

将它拼凑在一起后,我在我自己的程序中完成了所有操作,但我不知道在我的代码中调用drawLineFrom(fromPoint:CGPoint,toPoint:CGPoint)的位置,所以我可以实际绘制。该应用程序运行,但我仍然无法绘制。代码如下。

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) {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)

    tempImageView.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()

    tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    tempImageView.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)
    }
}

let tempImageView = UIImageView()

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor(r: 21, g: 221, b: 125)

    //view.addSubview(titleLabel)
    //view.addSubview(learnButton)
    //view.addSubview(drawButton)
    //view.addSubview(mainImageView)
    view.addSubview(tempImageView)


    //setupTitleLabel()
    //setupLearnButton()
    //setupDrawButton()
    setupImageViews()

    self.navigationController?.isNavigationBarHidden = true
}

func setupImageViews() {
    tempImageView.widthAnchor.constraint(equalTo: view.widthAnchor)
    tempImageView.heightAnchor.constraint(equalTo: view.heightAnchor)
}

0 个答案:

没有答案