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

iOS: Remove last image in array after touchesEnded has been completed

我正在构建一个 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")

}

在删除最后一个对象之前检查图像数组是否有对象。

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