Ios 移动UIImageView

Ios 移动UIImageView,ios,iphone,cocoa-touch,uikit,core-animation,Ios,Iphone,Cocoa Touch,Uikit,Core Animation,沿点阵列移动图像的最佳方法是什么?最简单的方法是使用 这是一个简单的示例,假设您能够使用UIImageView保存图像,使用NSArray保存观点 UIImage *image = [UIImage imageNamed:@"image.png"]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; [someView addSubview:imageView]; // Assume

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

最简单的方法是使用

这是一个简单的示例,假设您能够使用UIImageView保存图像,使用NSArray保存观点

    UIImage *image = [UIImage imageNamed:@"image.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    [someView addSubview:imageView]; // Assume someView exists

    NSValue *firstPoint = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
    NSValue *secondPoint = [NSValue valueWithCGPoint:CGPointMake(100, 0)];
    NSValue *thirdPoint = [NSValue valueWithCGPoint:CGPointMake(100, 100)];
    // And so on....

    NSArray *points = [NSArray arrayWithObjects:firstPoint, secondPoint, thirdPoint, nil];

    for (NSValue *pointValue in points) {

        [UIView beginAnimations:@"UIImage Move" context:NULL];

        CGPoint point = [pointValue CGPointValue];
        CGSize size = imageView.frame.size;

        imageView.frame = CGRectMake(point.x, point.y, size.width, size.height);

        [UIView commitAnimations];
    }

我建议的方法是将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的帧,因此如果稍后引用该帧,则可能需要将其考虑在内,或者为动画结束添加委托方法回调以将其设置为正确的值

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


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

实际上,这不会正常工作,因为您将同时启动这三个移动。动画发生在背景线程上,您需要等待它们完成。你的动画行为将是不可预测的,而不是沿着一条路径移动。我有很多正在进行的处理(多线程),这导致了延迟,所以这个动画甚至没有被执行,它只是非常跳跃。。。有没有办法将CAKeyFrameAnimation放在线程中并赋予它执行的最高优先级?