0

Basically I would just like to touch the image and have it move with my finger across the screen without using theImage.center = touchPosition I don't want to have the center snap to my finger. I want to move the image from whatever point I touch.

user2037857
  • 83
  • 1
  • 8

1 Answers1

2

The standard way to handle this, which @richard-j-ross-iii hinted at in a comment, is to save the difference between the view's center and the touch position when the drag starts and then maintain that difference as the drag proceeds. In your touchesBegan:withEvent: method save the offset like:

_dragOffsetFromCenter = CGSizeMake(touchLocationInImageView.x - centerOfImageView.x, touchLocationInImageView.y - centerOfImageView.y);

then in touchesMoved:withEvent: you can maintain that same offset like:

myImageView.center = CGPointMake(touchLocation.x - _dragOffsetFromCenter.x, touchLocation.y - _dragOffsetFromCenter.y);
Aaron Golden
  • 7,092
  • 1
  • 25
  • 31
  • how I can calculate touchLocationInImageView? – user2037857 Mar 25 '13 at 17:44
  • The various `touches:*` methods receive an `NSSet` of UITouch objects when they are called by UIKit. Take one of the touches in that set (if you aren't supporting multi-touch on these views just use `[touches anyObject]` to get the one touch), then `touchLocationInImageView = [theTouch locationInView:myImageView];` – Aaron Golden Mar 25 '13 at 17:55
  • because for example myImage (100,100) and when touch in left up corner (of myImage) 20,20 then _dragOffsetFromCenter = width (-30) height (-30) – user2037857 Mar 25 '13 at 18:18
  • That should be fine. In your example, suppose you drag one pixel to the right, to (21,20). Then the new image view center x will be 21 - (-30) = 51, which is one pixel to the right of the previous center. That's the result you want, isn't it? – Aaron Golden Mar 25 '13 at 18:36
  • Actually `[theTouch locationInView:myImageView]` might not work for you because the image view is moving. The coordinate system changes throughout the drag. Better to use a consistent coordinate system throughout the drag by (for example) working with the touch positions in the superview of the image view. – Aaron Golden Mar 25 '13 at 18:40