2011-10-25 37 views
1

我试图做一个简单的应用程序,其中“固定”ge的图像被手指移动后返回到它的位置。这可能与代码更好地解释:了解CGAffineTransform交互

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    image.transform = CGAffineTransformIdentity; 
} 


- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    UITouch *touch = [[event allTouches] anyObject]; 
    if (CGRectContainsPoint([image frame], [touch locationInView:nil])) 
    { 
     image.center = [touch locationInView:nil]; 
    } 
} 

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
    if (pin) { 
     CGPoint point = image.center; 
     CGPoint center = self.view.center; 
     //CGAffineTransform transform = CGAffineTransformMakeTranslation(0, 0); 
     [UIView beginAnimations:nil context:NULL]; 
     [UIView setAnimationDuration:0.5]; 
     image.transform = CGAffineTransformMakeTranslation(center.x - point.x, center.y - point.y); 
     //image.transform = CGAffineTransformConcat(image.transform, CGAffineTransformMakeTranslation(center.x - point.x, center.y - point.y)); 
    [UIView commitAnimations]; 

    } 
} 

每当我按下图像,它会移动,以便它从我的手指下移出。我认为这与转变有关。任何人都可以请指出我的方向正确吗?

回答

1

EDITED

其实我不喜欢这样写道:

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


- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    CGPoint location = [[touches anyObject] locationInView:[touch view]]; 
    CGPoint difference = CGPointMake(location.x - image.center.x, location.y - image.center.y); 

    image.transform = CGAffineTransformTranslate(image.transform, difference.x, difference.y); 
} 

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
    if (pin) { 
     [UIView beginAnimations:nil context:NULL]; 
     [UIView setAnimationDuration:0.5]; 
     image.transform = CGAffineTransformIdentity; 
     [UIView commitAnimations]; 
    } 
} 
+0

工作很好!虽然我确实需要添加 UITouch * touch = [[event allTouches] anyObject]; 为了代码工作(我也需要检查边界)。谢谢! – Eric

3

我想你应该只使用

image.transform = CGAffineTransformMakeTranslation(difference.x, difference.y); 

的方式你这样做是你积累了更多的以及touchesMoved的每次迭代更多的翻译。中心属性不依赖于我认为的变换。

+0

我已经结合了两种不同来源的技术:P。谢谢! – Eric