繁体   English   中英

移动UIImageView

[英]Move a UIImageView

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

我推荐的方法是将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()的调用,使图像沿曲线而不是直线移动。

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

最简单的方法是使用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];
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM