metsburg
metsburg

Reputation: 2021

XCode - Exact relative coordinates of touch event on image - iOS

I'm trying to build a simple photo crop utility where user can touch and select the picture boundary. I need the exact touch coordinates w.r.t the image.

When I use

    CGImageRef imageRef = [staticBG.image CGImage];
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[self view]];
    y3=location.y;
    x3=location.x;

the coordinates (x3,y3) comes in absolute scale and is not useful for handling imageRef.

I tried using

    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:staticBG];

but still the coordinates do not quite match up.

Please help.

Upvotes: 0

Views: 4479

Answers (2)

Jason Lee
Jason Lee

Reputation: 3250

I don't think we need exact coordinates from the user touch, but to crop the image I will :

  1. Layout a maskView on the image to let the user choose the area to crop. The maskView has a exact frame that can be easily known.
  2. Detect the user touch using touchesBegan and touchesMoved. While the user touch moves, move the maskView as well (change maskView's frame). In this step, we need to decide that which vertex of the maskView is the closest to the Point that user touched -- leftTop, rightTop, leftBottom or rightBottom.
  3. On touchesEnded, we use the maskView's frame to crop the image. Here, the coordinates is exact enough. Notice that we need to change the maskView's frame for image's coordinate system.

Hope helps. :)

Upvotes: 0

iPatel
iPatel

Reputation: 47059

use following code :)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

        UITouch *touch = [touches anyObject];

        if ([touch tapCount] == 2) {
            //self.imageView.image = nil;
            return;
        }

        CGPoint lastPoint = [touch locationInView:self.YourImageView];
        NSLog(@"%f",lastPoint.x);
        NSLog(@"%f",lastPoint.y);

    }

Upvotes: 2

Related Questions