如何使UIImageView闪烁/闪光动画无限循环?

7

我正在尝试在我的iOS应用程序中,使用一些持续时间为UIImageView实现闪烁/闪光效果。我希望UIImageView通过alpha值闪烁/闪光,而不是使用不同的图像。

我有另一个来自Android应用程序的代码片段,它描述了我正在尝试在XCode Swift中实现的效果。我在下面发布它:

这是我目前在XCode Swift中实现的:

        ellipses.alpha=0.8
        ellipses.animationDuration=1
        ellipses.animationRepeatCount=0
        ellipses.startAnimating()

当然,它没有起作用!我不是很确定如何实现这一点,非常希望得到一些指导。 下面的代码是针对 Android 而不是 Swift/Xcode 的(但它描述了我的目标相当清楚)。
        Animation animation = new AlphaAnimation(1, 0); //to change visibility from visible to invisible
        animation.setDuration(1000); //1 second duration for each animation cycle
        animation.setInterpolator(new LinearInterpolator());
        animation.setRepeatCount(Animation.INFINITE); //repeating indefinitely
        animation.setRepeatMode(Animation.REVERSE); //animation will start from end point once ended.
        imageButton.startAnimation(animation); //to start animation

使用 UIView 动画。 - Mannopson
可以参考以下链接:https://dev59.com/12025IYBdhLWcg3wFxua#39936878 - MS_iOS
3个回答

11
您可以重复动画图像视图的不透明度。类似这样:
UIView.animate(withDuration: 2.0,
                      delay: 0,
                    options: [.repeat, .autoreverse],
                 animations: { imageView.alpha = 0 }
              )

“UIImageView?”类型的值没有“opacity”成员。” - Logi95
@Logi95 使用 "alpha"。 - padam thapa

8

使用以下代码可以实现图像闪烁的动画效果。

图像闪烁(使用图像视图隐藏/显示):

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.alarmAlertActivate), userInfo: nil, repeats: true)
    }

    @objc func alarmAlertActivate(){
        myImage.isHidden = !myImage.isHidden
    }

这里输入图片描述

图片闪烁(使用图片视图alpha):

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.alarmAlertActivate), userInfo: nil, repeats: true)
    }

@objc func alarmAlertActivate(){
        UIView.animate(withDuration: 0.7) {
            self.alarmImage.alpha = self.alarmImage.alpha == 1.0 ? 0.0 : 1.0
        }
    }

enter image description here


谢谢,运行得很好! 我想在上面加一些不透明度/alpha,您有关于如何实现它的建议吗? - Logi95
是的,您可以更改UIImageView的alpha值,稍等我会更新我的代码。 - AtulParmar

1
我想让我的按钮突然闪烁/闪光,而不是像大多数IOS动画默认情况下平稳地淡入淡出。上面的接受答案使用计时器来实现这一点,但你也可以设置常规的动画类来实现这一点--而不会平滑。以下是一个示例,它使按钮的边框颜色闪烁,但这可以用于任何需要相同效果的东西。
这里的诀窍是使用“关键帧”动画,并将calculationMode设置为“离散”。
    let color = CAKeyframeAnimation(keyPath: "borderColor")
    color.values = [CGColor.white, CGColor.black, CGColor.white]
    color.keyTimes = [0, 0.5, 1]
    color.duration = 1
    color.repeatCount = .infinity
    color.calculationMode = .discrete
    gotItButton.layer.borderWidth = 3
    gotItButton.layer.add(color, forKey: "")

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