需求
在一个TextView
里面有个背景图片,需要这个背景图片旋转。
实现
要使 TextView 中的图片旋转,可以使用 Animation 动画来实现.
示例代码:
val imageView: ImageView = findViewById(R.id.imageView)
val rotateAnimation = RotateAnimation(
0f,
360f,
Animation.RELATIVE_TO_SELF,
0.5f,
Animation.RELATIVE_TO_SELF,
0.5f
)
rotateAnimation.duration = 1000
rotateAnimation.interpolator = LinearInterpolator()
rotateAnimation.repeatCount = Animation.INFINITE
imageView.startAnimation(rotateAnimation)
在上面的代码中,我们首先获取了要旋转的 ImageView 对象,并创建了一个 RotateAnimation
对象。这里我们将旋转的角度从 0 度到 360 度,并以 View 自身的中心
作为旋转点。我们还设置了动画持续时间、插值器(使动画匀速执行)、动画重复次数并使用 startAnimation()
方法启动动画。
如果想要更改动画的属性,比如旋转速度或者旋转中心点位置,可以调整 RotateAnimation 的构造函数参数。
在上面的 Kotlin 代码示例中,可以看出动画重复次数设置的是 repeatCount
属性,这个属性决定动画的重复次数,类型为整型。如果设置为 Animation.INFINITE,则表示动画将无限循环执行,直到手动停止。可以通过调用cancel()
方法来手动停止动画的执行。
rotateAnimation.repeatCount = Animation.INFINITE
如果想要指定动画的重复次数,请将 repeatCount 属性设置为正整数值。例如,如果将其设置为 3,则动画将在执行三次后停止。