我有一个 kotlin Gif 十进制代码,但我希望这段代码是用 java 编写的



我正在研究GIF解码器。代码工作正常。只认为我对 kotlin 完全陌生,所以无法理解中使用的语法。所以我完全迷失了。帮助我用Java编写相同的代码。我希望此代码用于主活动(Java(。但是当前的代码是为 Kotlin 中的片段编写的。

这个图书馆使用了 https://github.com/koral--/android-gif-drawable

法典:

class GifDecoderFragment : BaseFragment(), CoroutineScope {
    private val job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job
    private var frames = emptyList<Bitmap>()
    private var durations = emptyList<Int>()
    private var currentFrameIndex = 0
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.decoder, container, false)
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        launch(Dispatchers.IO) {
            val frames = mutableListOf<Bitmap>()
            val durations = mutableListOf<Int>()
            val decoder = GifDecoder(InputSource.ResourcesSource(resources, R.drawable.room3))
            for (i in 0 until decoder.numberOfFrames) {
                val frame = Bitmap.createBitmap(decoder.width, decoder.height, Bitmap.Config.ARGB_8888)
                decoder.seekToFrame(i, frame)
                Log.d("BaseActivityneww", "onCreate: $i")
                frames += frame
                durations += decoder.getFrameDuration(i)

            }
            decoder.recycle()
            withContext(Dispatchers.Main){
                this@GifDecoderFragment.frames = frames
                this@GifDecoderFragment.durations = durations
                if (isAdded) {
                    startAnimation()
                    decoderLoadingTextView.visibility = View.GONE
                }
            }
        }
    }
    override fun onResume() {
        super.onResume()
        if (frames.isNotEmpty()) {
            startAnimation()
        }
    }
    private fun startAnimation() {
        decoderImageView.setImageBitmap(frames[currentFrameIndex])

        launch {
            delay(durations[currentFrameIndex].toLong())
            advanceAnimation()
        }
    }
    override fun onPause() {
        job.cancelChildren()
        super.onPause()
    }
    override fun onDestroy() {
        job.cancel()
        super.onDestroy()
    }
    private fun advanceAnimation() {
        currentFrameIndex++
        currentFrameIndex %= frames.size
decoderImageView.setImageBitmap(frames[currentFrameIndex])
launch {
            delay(durations[currentFrameIndex].toLong())
            advanceAnimation()
        }
    }

Xml:

 <ImageView
        android:id="@+id/decoderImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

如果您使用的是 Android Studio,则可以使用 Kotlin 插件:

> Tools> Kotlin

的菜单 -> 将 Kotlin 反编译为 Java。

最新更新