沿着点阵列移动图像的最佳方式是什么?
最佳答案
我推荐的方法是将 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/