使用jetPack Compose Image替换AnimationDrawable

问题描述 投票:0回答:1

我想用 Jetpack Compose API 替换我在 xml 中创建的视图。

但现在我坚持更换我的 AnimationDrawable。

我用它来制作“充电动画”,开始转换 3 个图像(低电量、中电量和满电量图像)

所以当手机充电时,我通过调用 TimerTask 来启动动画以无限启动动画,直到手机与电源断开连接。

private class MyTimerTask(private val transitionDrawable: AnimationDrawable) : TimerTask() {
    override fun run() {
        Dispatcher.runOnUiThread {
            transitionDrawable.start()
        }
    }
}

init {
    drawLow = AppCompatResources.getDrawable(context, R.mipmap.low_battery)
    drawMid = AppCompatResources.getDrawable(context, R.mipmap.mid_battery)
    drawFull = AppCompatResources.getDrawable(context, R.mipmap.full_battery)

    if (drawLow !== null && drawMid != null && drawFull != null) {
        mTransitionDrawable.addFrame(drawLow, 500)
        mTransitionDrawable.addFrame(drawMid, 500)
        mTransitionDrawable.addFrame(drawFull, 500)
    }
}

我如何使用 compose API 来做到这一点?我必须将 png 文件转换为 ImageBitmap。所以我不能再使用 AnimationDrawable 了。

((ResourcesCompat.getDrawable(context.resources, R.mipmap.low_battery, context.theme) as BitmapDrawable).bitmap).asImageBitmap()

那么如何实现“充电动画”呢?

android kotlin animation android-jetpack-compose android-drawable
1个回答
0
投票

1、

build.gradle
配置
useSupportLibrary
属性:

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.your.package.xxxx"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        vectorDrawables {
            useSupportLibrary true
        }
    }
}

2、依赖关系

implementation "com.google.accompanist:accompanist-drawablepainter:0.28.0"

3、显示

val animationDrawable = AnimationDrawable()
//add your images in animationDrawable by giving information of duration etc like you gave in xml file..
Image(
    painter = rememberDrawablePainter(animationDrawable),
    contentDescription = null,
    modifier = Modifier.wrapContentSize(), 
    contentScale = ContentScale.Crop
)

animationDrawable?.start()
© www.soinside.com 2019 - 2024. All rights reserved.