Android Animation (2) Colección de animación

1. Colección de animación

Clase:

  • La
    función AnimationSet es débil y no se puede personalizar para organizar las animaciones en el conjunto en un orden determinado y luego ejecutarlas.
  • AnimatorSet

Ninguno de los dos establece funciones duplicadas. . .


1, AnimationSet

Uso:

class MainActivity : AppCompatActivity() {
    var TAG = "Animation"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val button = findViewById<Button>(R.id.btn)
        val animationSet = AnimationSet(true) //true—让这些动画共用AnimationSet设置插值器
        val alphaAnimation = AlphaAnimation(0f, 1f)
        alphaAnimation.duration = 3000
        val rotateAnimation = RotateAnimation(0f,360f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f)
        rotateAnimation.duration = 3000
        alphaAnimation.repeatCount = Animation.INFINITE
        rotateAnimation.repeatCount = Animation.INFINITE
        animationSet.addAnimation(alphaAnimation)
        animationSet.addAnimation(rotateAnimation)
        animationSet.interpolator = AccelerateDecelerateInterpolator()
        button.startAnimation(animationSet)
    }
}

Tenga en cuenta que no puede configurar el bucle en AnimationSet, porque no funcionará si se configura.
Inserte la descripción de la imagen aquí


2 、 AnimatorSet

Hay dos formas de agregar animación a AnimatorSet:

  • Puede llamar al método playTogether (Animator []) de AnimatorSet o playSequentially (Animator []) de AnimatorSet para agregar un conjunto de animaciones a la vez
  • También puede utilizar el método de reproducción AnimatorSet (Animator) junto con los métodos de la clase AnimatorSet.Builder para agregar animaciones una por una.

Todavía no hay forma de establecer un bucle en AnimatorSet
Vamos:
playTogether (Animator [])
Inserte la descripción de la imagen aquí
simplemente deja que la animación comience de forma conjunta, pero el proceso y el resultado están definidos por cada animación

class MainActivity : AppCompatActivity() {
    var TAG = "Animation"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun click(view: View) {
        val animatorSet = AnimatorSet()
        val button = findViewById<Button>(R.id.btn)
        val backgroundColorAnimator = ObjectAnimator.ofInt(button, "BackgroundColor", Color.WHITE, Color.BLACK, Color.WHITE)
        val rotation= ObjectAnimator.ofFloat(button, "Rotation", 0f, 360f)
        animatorSet.playTogether(backgroundColorAnimator, rotation)
        animatorSet.duration = 3000
        animatorSet.start()
    }
    fun click2(view: View) {
        val animatorSet = AnimatorSet()
        val button2 = findViewById<Button>(R.id.btn2)
        val backgroundColorAnimator = ObjectAnimator.ofArgb(button2, "BackgroundColor", Color.WHITE, Color.BLACK, Color.WHITE)
        val rotation= ObjectAnimator.ofFloat(button2, "Rotation", 0f, 360f)
        animatorSet.playTogether(backgroundColorAnimator, rotation)
        backgroundColorAnimator.duration = 3000
        rotation.duration = 6000
        animatorSet.start()
    }
}

Inserte la descripción de la imagen aquí
Primero establecemos un tiempo de ejecución diferente para cada animación en el segundo botón

Aquí llega la comprensión de la diferencia entre lo siguiente deInt setting color y ofArgb

  • ofInt se acumula un poco desde el color inicial hasta el color objetivo.
  • Se puede entender que ofArgb establece el efecto de gradiente que usualmente establecemos con ps.


ejecución secuencial de playSequentially (Animator [])
Inserte la descripción de la imagen aquí

class MainActivity : AppCompatActivity() {
    var TAG = "Animation"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun click(view: View) {
        val animatorSet = AnimatorSet()
        val button = findViewById<Button>(R.id.btn)
        val backgroundColorAnimator = ObjectAnimator.ofInt(button, "BackgroundColor", Color.WHITE, Color.BLACK, Color.WHITE)
        val rotation= ObjectAnimator.ofFloat(button, "Rotation", 0f, 360f)
        animatorSet.playSequentially(backgroundColorAnimator, rotation)
        animatorSet.duration = 3000
        animatorSet.start()
    }
    fun click2(view: View) {
        val animatorSet = AnimatorSet()
        val button2 = findViewById<Button>(R.id.btn2)
        val backgroundColorAnimator = ObjectAnimator.ofArgb(button2, "BackgroundColor", Color.WHITE, Color.BLACK, Color.WHITE)
        val rotation= ObjectAnimator.ofFloat(button2, "Rotation", 0f, 360f)
        animatorSet.playSequentially(backgroundColorAnimator, rotation)
        backgroundColorAnimator.duration = 3000
        rotation.duration = 6000
        animatorSet.start()
    }
}

Inserte la descripción de la imagen aquí
A través de los dos efectos de botón, descubrimos que
       cuando la duración se establece en AnimatorSet, cada animación tendrá una duración de una duración, la duración total: n * duración

Para el problema playSequentially loop, tome lo anterior como ejemplo: si establece un bucle infinito en la primera animación, la segunda animación nunca se ejecutará y establecer la duración en Animación tampoco es válido. A menos que lo cancele manualmente

AnimatorSet.Builder
constructor
tres funciones de uso común:

  • Uso común:animatorSet.play().with().before().after()
  1. con animación
  2. antes del precedente
  3. despues
  4. play devuelve un objeto AnimatorSet.Bulider

Entonces, ¿qué secuencia de animación es? Recuerda:

  • A después de ejecutar BA después de ejecutar B
  • A antes de ejecutar BA antes de ejecutar B

Verificarlo:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun click(view: View) {
        val animatorSet = AnimatorSet()
        val button = findViewById<Button>(R.id.btn)
        val backgroundColorAnimator = ObjectAnimator.ofInt(button, "BackgroundColor", Color.WHITE, Color.BLACK, Color.WHITE)
        val rotation = ObjectAnimator.ofFloat(button, "Rotation", 0f, 360f)
        animatorSet.duration = 3000
        animatorSet.play(backgroundColorAnimator).before(rotation)
        animatorSet.start()
    }
    fun click2(view: View) {
        val animatorSet = AnimatorSet()
        val button2 = findViewById<Button>(R.id.btn2)
        val backgroundColorAnimator = ObjectAnimator.ofArgb(button2, "BackgroundColor", Color.WHITE, Color.BLACK, Color.WHITE)
        val rotation = ObjectAnimator.ofFloat(button2, "Rotation", 0f, 360f)
        backgroundColorAnimator.duration = 3000
        rotation.duration = 6000
        animatorSet.play(backgroundColorAnimator).after(rotation)
        animatorSet.start()
    }
}

Inserte la descripción de la imagen aquí


¿Cómo pueden reproducirse estas complejas secuencias de animación repetidamente? Mira el código a continuación:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun click2(view: View) {
        val animatorSet = AnimatorSet()
        val button2 = findViewById<Button>(R.id.btn2)
        val backgroundColorAnimator = ObjectAnimator.ofArgb(button2, "BackgroundColor", Color.WHITE, Color.BLACK, Color.WHITE)
        val rotation = ObjectAnimator.ofFloat(button2, "Rotation", 0f, 360f)
        backgroundColorAnimator.duration = 3000
        rotation.duration = 6000
        animatorSet.play(backgroundColorAnimator).after(rotation)
        animatorSet.addListener(object : Animator.AnimatorListener{
            override fun onAnimationRepeat(animation: Animator?) {

            }

            override fun onAnimationEnd(animation: Animator?) {
                animation?.start()
            }

            override fun onAnimationCancel(animation: Animator?) {
            }

            override fun onAnimationStart(animation: Animator?) {
            }
        })
        animatorSet.start()
    }
}

Inserte la descripción de la imagen aquí

Una vez completada la ejecución de la animación, vuelva a
abrirla . Tenga en cuenta que aunque onAnimationEnd ha pasado una animación aquí, no significa todas las animaciones, sino una gran animación sintetizada por cada animación en el hogar humano, por lo que no será desordenada.
La siguiente sección ingresa el estimador del interpolador y el uso de Object ().
Espero aprender de usted.

Publicado 16 artículos originales · me gusta 0 · visitas 249

Supongo que te gusta

Origin blog.csdn.net/weixin_43860530/article/details/105346998
Recomendado
Clasificación