iOS:在touchesEnded完成后删除数组中的最后一个图像

时间:2018-05-21 11:01:10

标签: ios arrays image touch cgpoint

我正在构建一个iOS绘图应用程序,我正在尝试实现一个撤消按钮来删除用户绘制的线条。我在变量中创建了一个图像数组:

var images = [UIImage]()

每次用户从屏幕上滑动并移开手指时,都会在touchesEnded功能中创建新图像。我想我需要删除最后一张图像以获取IBAction中的上一张图像,该图像将充当撤消按钮。

以下是我当前代码的示例:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch = touches.first!
    guard touch.view != floaty else { return }



    swiped = false
    if let touch = touches.first{
        postBtn.isEnabled = true
        postBtn.setImage(UIImage(named: "done_icon_moved"), for: .normal)


        dismissBtn.isEnabled = true

        undoBtn.isEnabled = true
        undoBtn.setImage(UIImage(named: "undo_icon_moved"), for: .normal)


        lastPoint = touch.location(in: self.view)

    }
}

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

    // 1
    UIGraphicsBeginImageContext(view.frame.size)

    tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
    let context = UIGraphicsGetCurrentContext()
    // 2

    context?.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
    context?.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))

    // 3

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

    // 4
    context?.strokePath()

    // 5
    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
        drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)

    }

    // Merge tempImageView into mainImageView


    UIGraphicsBeginImageContext(mainImageView.frame.size)
    mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height),blendMode: CGBlendMode.normal, alpha: 1.0)
    tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: CGBlendMode.normal, alpha: opacity)
    mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    tempImageView.image = nil

    print("touch ended")

}

1 个答案:

答案 0 :(得分:1)

在删除最后一个对象之前,检查图像阵列是否有对象。

if images.count != 0 {
   images.removeLast()
}