Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Store image in a var then press a button to remove one of the images in the array

I am creating a drawing app in Swift. In which every time a user draws a line on the UIImageVIew it rasterizes a new image. I would like to create an undo button which goes to the previous image in the array.

Here is my code -

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
floaty.isHidden = false
postBtn.isHidden = false
resetBtn.isHidden = false
undoBtn.isHidden = false
dismissBtn.isHidden = false

}