0

I have this code to drag an imageView:

in touchbegan:

CGPoint point = [touch locationInView:self];
[imageView setCenter:point];

in touchmoved:

CGPoint point = [touch locationInView:self];
[imageView setCenter:point];

this code allow to have imageview ever under my finger and move it form its center. But I want something that allow me drag an imageview not only from center of imageview but also from another point of imageview...and not drag it if I touch out of this imageView... can you help me?

cyclingIsBetter
  • 17,447
  • 50
  • 156
  • 241

2 Answers2

0

Instead of just setting the center point to the touch point you need to work out how the touch has moved.

Store the touch point in a variable.

In touchesBegan...

storedPoint = [touchLocationInView:self];

Then in touchesMoved...

CGPoint currentPoint = [touch locationInView:self];

CGPoint vector = CGPointMake(currentPoint.x - storedPoint.x, currentPoint.y storedPoint.y);

[imageView setCenter:CGPointMake(imageView.center.x + vector.x, imageView.center.y + vecotr.y)];

storedPoint = currentPoint;

Something like this anyway.

To ignore the touch you could say in touchesBegan...

if (!CGRectContainsPoint(imageView.frame, [touch locationInView:self])
{
    //ignore touch
    trackTouches = NO;
}

trackTouches = YES;

(trackTouches is a class var)

Then in touchesMoved only do stuff if trackTouches == YES.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
0

You'll need to: A) Test that the touch is in the imageView B) Calculate the difference between the touch and the center of the imageView. Once you know that x/y difference, you can do some simple math to move the center relative to where on the imageView the user has touched.

There are plenty of examples on this site for A, and B should be straight-forward.

HackyStack
  • 4,887
  • 3
  • 22
  • 28