当我拖动uiimageview
时,中心位于点击位置。我正在使用以下代码
imageView.center=[[touches anyObject] locationInView:self.view];
所以即使我在角落拖动鼠标也会跳到图像中心。
如何让鼠标定位在imageview的点击位置。???
提前完成
答案 0 :(得分:2)
我想你想要移动你的imageView并且imageView正在“无心地”将它的中心移动到你的接触点......
如果您不希望imageView在触摸时设置其中心,但是从用户触摸的任何点拖动它,跟踪他触摸的第一个CGPoint,然后重新定位图像在前两个接触点之间的相对距离
@interface myViewController : UIViewController {
CGPoint touchPoint;
BOOL touchedInside;
}
@end
@implementation myViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
touchPoint = [touch locationInView:self.view];
CGPoint pointInside = [touch locationInView:imageView];
if ([imageView pointInside:pointInside withEvent:event])
touchedInside = YES;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if (touchedInside) {
UITouch *touch = [touches anyObject];
CGPoint newPoint = [touch locationInView:self.view]; // get the new touch location
imageView.center = CGPointMake(imageView.center.x + newPoint.x - touchPoint.x, imageView.center.y + newPoint.y - touchPoint.y); // add the relative distances to the imageView.center
touchPoint = newPoint; // assign the newest touch location to the old one
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
touchedInside = NO;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (touchedInside) {
UITouch *touch = [touches anyObject];
CGPoint newPoint = [touch locationInView:self.view];
imageView.center = CGPointMake(imageView.center.x + newPoint.x - touchPoint.x, imageView.center.y + newPoint.y - touchPoint.y);
}
touchedInside = NO;
}
@end