package com.xm.test.myfilemaster.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.util.AttributeSet
import android.view.View
import com.xm.test.myfilemaster.R

class RotatingImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private var bitmap: Bitmap? = null
    private var matrix: Matrix = Matrix()
    private var rotationAnimator: ValueAnimator? = null
    private var rotationAngle: Float = 0f

    init {
        // 加载图片
        bitmap = BitmapFactory.decodeResource(resources, R.mipmap.loading)


        // 创建旋转动画
        rotationAnimator = ValueAnimator.ofFloat(0f, 360f)
        rotationAnimator?.apply {
            repeatCount = ValueAnimator.INFINITE
            duration = 2000 // 旋转一周的时间
            addUpdateListener { animation ->
                rotationAngle = animation.animatedValue as Float
                invalidate()
            }
            start()
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 如果没有图片，直接返回
        bitmap?.let {
            // 保存画布状态
            canvas.save()

            // 旋转图片
            matrix.setRotate(rotationAngle, it.width / 2f, it.height / 2f)
            canvas.drawBitmap(it, matrix, null)

            // 恢复画布状态
            canvas.restore()
        }
    }
}
