【问题标题】:Animate UIImage in UIImageView Up & Down (Like it's hovering) LoopUIImageView 中的 UIImage 动画向上和向下(就像悬停一样)循环
【发布时间】:2012-10-14 10:00:19
【问题描述】:

您好,我有一张图片,我想上下移动(上移 10 像素和下移 10 像素),以便我的图片看起来像是在悬停。我怎么能用简单的动画做到这一点非常感谢!!!

【问题讨论】:

    标签: ios animation uiimageview core-animation ios6


    【解决方案1】:

    您可以使用 Core Animation 为视图层的位置设置动画。如果您将动画配置为additive,您就不必费心计算新的绝对位置,只需计算变化(相对位置)。

    CABasicAnimation *hover = [CABasicAnimation animationWithKeyPath:@"position"];
    hover.additive = YES; // fromValue and toValue will be relative instead of absolute values
    hover.fromValue = [NSValue valueWithCGPoint:CGPointZero];
    hover.toValue = [NSValue valueWithCGPoint:CGPointMake(0.0, -10.0)]; // y increases downwards on iOS
    hover.autoreverses = YES; // Animate back to normal afterwards
    hover.duration = 0.2; // The duration for one part of the animation (0.2 up and 0.2 down)
    hover.repeatCount = INFINITY; // The number of times the animation should repeat
    [myView.layer addAnimation:hover forKey:@"myHoverAnimation"];
    

    由于这是使用 Core Animation,您需要将 QuartzCore.framework 和 #import <QuartzCore/QuartzCore.h> 添加到您的代码中。

    【讨论】:

    • 哇,伙计,这工作得更好!不仅更容易理解,而且我实际上可以尝试不同的有意义的值!非常感谢!!!
    【解决方案2】:

    对于 Swift 3、Swift 4 和 Swift 5:

    let hover = CABasicAnimation(keyPath: "position")
        
    hover.isAdditive = true
    hover.fromValue = NSValue(cgPoint: CGPoint.zero)
    hover.toValue = NSValue(cgPoint: CGPoint(x: 0.0, y: 100.0))
    hover.autoreverses = true
    hover.duration = 2
    hover.repeatCount = Float.infinity
        
    myView.layer.add(hover, forKey: "myHoverAnimation")
    

    【讨论】:

      【解决方案3】:

      试试这个:

      CGRect frm_up = imageView.frame;
      frm_up.origin.y -= 10;
      
      [UIView animateWithDuration:0.5
          delay:0.0
          options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeats
          animations:^{
              imageView.frame = frm_up;
          }
          completion:NULL
      ];
      

      【讨论】:

      • 效果很好!唯一的问题是它向上和向左移动。对角线就像它会到达 0,0 标记。
      • @Year3000 怎么样? 1.我对框架的X方向完全没有做任何事情。 2. 我唯一改变的是 y 位置,但是它应该是自动反转的(参见方法调用的options 参数)。我确定你错过了什么。
      • IDK 这很奇怪。我的框架是 (86, 198, 132, 217) 并且我正在使用您推荐的框架,就像 imageView 的中心指向 0,0。
      • 如何从上到下旋转图像
      【解决方案4】:

      对于这样的任务,最好将图像放置在UIView 的子层中,然后为该子层帧设置动画。本教程可以给你一些想法:http://www.raywenderlich.com/2502/introduction-to-calayers-tutorial

      【讨论】:

      • 您链接到的教程没有解释如何制作动画。
      • 图层上的操作是自动动画的。
      • 是的,如果它们是独立层,它们具有隐式动画,但它们不会返回动画等。
      猜你喜欢
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      相关资源
      最近更新 更多