移动一个UIImageView

4
什么是沿着一系列点移动图像的最佳方式?
2个回答

9

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

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

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


我有很多处理(多线程)正在进行,这导致了延迟,以至于这个动画甚至没有被执行,只是非常卡顿... 有没有办法将CAKeyFrameAnimation放在一个线程中,并赋予它最高的优先级来执行? - Albert Renshaw

1

最简单的方法是使用UIView动画

一个快速的示例,假设您能够使用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];
    }

3
实际上,那样做不会正常工作,因为你将同时触发这三个动画。动画发生在后台线程中,你需要等待它们完成。而不是沿着路径移动,你的动画行为将变得不可预测。 - Brad Larson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接