Search code examples
iosswiftuiimageviewtouchesbegan

Swift: How to create/define an area (width x height) where the user touched an image?


I am trying to define an area of let's say 80x80 pixel where the user touches an image (the touch location is in the center of the 80x80 rectangle).

I know how to get the touch location, but defining the area excels my knowledge right now.

This is what I did:

//the imageView which contains a user image
@IBOutlet weak var imageView: UIImageView!

//the touchesBegan function to get the touch location
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first!
        let location = touch.location(in: imageView)
    }

Now how could I create an area of 80x80 pixels with he touch location in the center and store it somewhere?

So X is the touch location and I'd like to define the area around it:

 -------
|       |
|   X   |
|       |
 -------

Solution

  • You can do it like this:

    let width: CGFloat = 80.0
    let height: CGFloat = 80.0
    let touchRectangle = CGRect(x: location.x - width / 2,
                                y: location.y - height / 2,
                                width: width ,
                                height: height)