im developing a game with some game field, which is drawn in some view. My game field always drawing relative to his center, so i have just simple pinch
- (void)pinch:(UIPinchGestureRecognizer *)gesture
{
if ((gesture.state == UIGestureRecognizerStateChanged) ||
(gesture.state == UIGestureRecognizerStateEnded)) {
self.gameBoardGridView.scale *= gesture.scale; // adjust our scale
gesture.scale = 1;
}
and pan
-(void)pan:(UIPanGestureRecognizer *)recognizer
{
CGPoint translatedPoint = [recognizer translationInView:self.gameBoardGridView];
self.gameBoardGridView.gridCenter = CGPointMake(self.gameBoardGridView.gridCenter.x + translatedPoint.x, self.gameBoardGridView.gridCenter.y + translatedPoint.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.gameBoardGridView];
}
but i need other kind of zoom. When you put two fingers down and then move one of them, the field expands (zooms in) like it should, but the pixels under the fingers are no longer under the finger. The image scales from the center of the image, not the mid point between the two fingers.
I tried a lot of examples, but nothing works like i want. Finally i wrote this, it works almost correct, but not completely
- (void)pinch:(UIPinchGestureRecognizer *)gesture
{
CGFloat curScale = gesture.scale;
static CGPoint startPoint;
if (gesture.state == UIGestureRecognizerStateBegan) {
startPoint = [gesture locationInView:self.gameBoardGridView];
}
if ((gesture.state == UIGestureRecognizerStateChanged) ||
(gesture.state == UIGestureRecognizerStateEnded)) {
self.gameBoardGridView.scale *= gesture.scale;
CGFloat widthDelta = self.gameBoardGridView.gridWidth * fabs(gesture.scale - 1) / 3;
CGFloat heightDelta = self.gameBoardGridView.gridHeight * fabs(gesture.scale - 1) / 3;
gesture.scale = 1;
CGPoint lastPoint = self.gameBoardGridView.gridCenter;
const CGFloat epsilon = 5;
CGFloat coef = 1.0;
if(curScale < 1) {
coef = -1.0;
}
if (startPoint.x + epsilon < self.view.frame.size.width / 2) {
lastPoint.x += widthDelta*coef;
}
else if (startPoint.x - epsilon > self.view.frame.size.width / 2) {
lastPoint.x -= widthDelta*coef;
}
if (startPoint.y + epsilon < self.view.frame.size.height / 2) {
lastPoint.y += heightDelta*coef;
}
else if (startPoint.y - epsilon > self.view.frame.size.height / 2) {
lastPoint.y -= heightDelta*coef;
}
self.gameBoardGridView.gridCenter = lastPoint;
}
}
May be there is other ways to do this?