Rotate an Imagewith Animation

前端 未结 6 1651
死守一世寂寞
死守一世寂寞 2021-02-01 04:23

\"The

What I Have

I have an arrow image (like the left one). Whe

6条回答
  •  长情又很酷
    2021-02-01 04:51

    If you want to rotate an image by 180 degrees clockwise.

    private var isExpanded = true
    
    private fun rotateImage(view: View) {
        val startAngle = if (isExpanded) 0f else 180f
        ObjectAnimator.ofFloat(view, View.ROTATION, startAngle, startAngle + 180f).apply {
            duration = 300
            interpolator = LinearInterpolator()
            start()
        }
        isExpanded = !isExpanded
    }
    

    Or more simply (as wrote @Alex.F):

    view.animate().setDuration(300).rotationBy(180f).start()
    

    Note that if you rotate the image many times too frequently, it doesn't stop in 0 - 180 - 360 positions. Because if you start a new animation before a previous finished, it will shift an angle.

    So, a better way is written in the accepted answer. It doesn't depend on current animation state.

    private var angle = 0f
    
    angle += 180f
    view.animate().setDuration(300).rotation(angle).start()
    

提交回复
热议问题