ios - 移动一个 UIImageView

标签 ios iphone cocoa-touch uikit core-animation

沿着点阵列移动图像的最佳方式是什么?

最佳答案

我推荐的方法是将 UIImage 包装在 UIImageView 中,并使用 CAKeyframeAnimation 沿着通过三个点的路径为 UIImageView 的图层设置动画:

UIImage *image = [UIImage imageNamed:@"image.png"];
imageView = [[UIImageView alloc] initWithImage:image];
[mainView addSubview:imageView];
// Remember to remove the image view and release it when done with it

CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
pathAnimation.duration = 1.0f;
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;

CGMutablePathRef pointPath = CGPathCreateMutable();
CGPathMoveToPoint(pointPath, NULL, viewOrigin.x, viewOrigin.y);
CGPathAddLineToPoint(pointPath, NULL, point1.x, point1.y);
CGPathAddLineToPoint(pointPath, NULL, point2.x, point2.y);
CGPathAddLineToPoint(pointPath, NULL, point3.x, point3.y);
pathAnimation.path = pointPath;
CGPathRelease(pointPath);

[imageView.layer addAnimation:pathAnimation forKey:@"pathAnimation"];

请注意,默认情况下,图层的位置位于图层的中心。如果您想相对于另一个引用点移动图层,您可以将图层的 anchorPoint 属性设置为类似 (0.0, 0.0) 的左上角(在 iPhone 上)或 (0.0, 1.0) 的左上角离开了。

此外,这不会在完成时更改 UIImageView 的框架,因此如果您稍后引用该框架,您可能需要考虑到这一点或为动画结束添加委托(delegate)方法回调将其设置为适当的值。

您还可以通过将对 CGPathAddLineToPoint() 的调用替换为 CGPathAddCurveToPoint() 来使图像沿曲线而不是直线移动。

编辑(2009 年 5 月 14 日):我添加了缺少的 pathAnimation.path = pointPath 行,并将对 curvedPath 的错误类型引用更改为 pointPath。

关于ios - 移动一个 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/862084/

相关文章:

ios - Objective c-只有特定的 UILabel 在 UITableView 中被编辑

iphone - 如何使用权利 key 访问私有(private) iOS 功能

iphone - 将 VOID 代码转换为 IBAction

iphone - 从 OpenGL View 显示 View Controller

ios - 即使满足条件(值为空),也不会显示警报 Controller

ios - Flurry 分析 "Table Failed to Load"错误

ios - 应用内购买是否适用于拥有 iOS 测试版的用户?

iphone - 如何在 iPhone 中追踪手指的长按操作?

iPhone:UIScrollView 内无限循环内容

iphone - UISearchDisplayController 和 UITableViewController