Brad Larson 为我指明了正确的道路,他建议将 UIImageView 放入 UIScrollView。
最后,我将UIImageView 放在UIScrollView 中,并将滚动视图的contentSize 和 imageView 的边界设置为与中的图像相同的大小UIImage:
UIImage* image = imageView.image;
imageView.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
scrollView.contentSize = image.size;
然后,我可以对scrollView的contentOffset进行动画处理,以实现漂亮的平移效果:
[UIView beginAnimations:@"pan" context:nil];
[UIView setAnimationDuration:animationDuration];
scrollView.contentOffset = newRect.origin;
[UIView commitAnimations];
在我的特定情况下,我正在平移到图像中的随机空间。为了找到一个合适的矩形来平移 to 和一个合适的持续时间来获得一个不错的恒定速度,我使用以下内容:
UIImage* image = imageView.image;
float xNewOrigin = [TCBRandom randomIntLessThan:image.size.width - scrollView.bounds.size.width];
float yNewOrigin = [TCBRandom randomIntLessThan:image.size.height - scrollView.bounds.size.height];
CGRect oldRect = scrollView.bounds;
CGRect newRect = CGRectMake(
xNewOrigin,
yNewOrigin,
scrollView.bounds.size.width,
scrollView.bounds.size.height);
float xDistance = fabs(xNewOrigin - oldRect.origin.x);
float yDistance = fabs(yNewOrigin - oldRect.origin.y);
float hDistance = sqrtf(powf(xDistance, 2) + powf(yDistance, 2));
float hDistanceInPixels = hDistance;
float animationDuration = hDistanceInPixels / speedInPixelsPerSecond;
我正在使用10.0f 中的speedInPixelsPerSecond,但其他应用程序可能想要使用不同的值。