Hi,
I'm learning Swift by following the great tutorials on this site, and I'm trying to write a simple Scratch Card game. I've figured out how to get two UIImageViews. You can pick a photo or take a picture to use in the background image view that needs to be revealed. The foreground image view loads a grey image, that then needs to be scratched away. I'm using a UIGraphicsImageRenderer to draw lines on the on grey image with a clear blendmode to cut through to see the image in the background image view.
The problem I'm having is tracking my finger to draw the lines, so I'm hoping you gues can help please. I'm using a Pan Gensture Recogniser and storing the location point in an array of CGPoints:
let location = gesture.location(in: view)
points.append(CGPoint(x: location.x, y: location.y))
My function that draws the picture and lines into the foregound image view is:
func drawLine(points: [CGPoint]) {
let image = foreGroundRenderer.image { ctx in
let fg = UIImage(named: "foreground")
fg?.draw(at: CGPoint(x: 0, y: 0))
if (points.count > 0) {
let firstPoint = points.first
ctx.cgContext.move(to: firstPoint!)
for pointIndex in 1..<points.count {
ctx.cgContext.addLine(to: points[pointIndex])
}
ctx.cgContext.setLineCap(.round)
ctx.cgContext.setLineWidth(50)
ctx.cgContext.setBlendMode(.clear)
ctx.cgContext.strokePath()
}
}
foreGround.image = image
}
I have two issues though.
1) The locations I store in my points array, track my finger but seem to be offset in both x and y. Is that a scaling issue with the size of the UIGraphicsImageRenderer?
2) What's the best place to call the drawLine function? I'm currently calling it in the Pan Gesture Recogniser IBAction, right after the line above where I append a new location to the array. While this seems to work, it very unresponsive and draws the lines quite slowly. I have a feeling there's a better place to call the drawLine function from but I'm not sure where.
Sorry my post is a bit long.
Mark