安卓加载动画文件

2018-04-18  本文已影响17人  hjm1fb

Fresco加载Gif动画

首先在gradle文件添加依赖

compile 'com.facebook.fresco:fresco:1.8.1'
compile 'com.facebook.fresco:animated-gif:1.8.1'

封装的接口如下(Kotlin):

/**
 * 加载本地Gif图片,宽度固定,高度等比缩放
 */
fun SimpleDraweeView.loadLocalGifByResizeLength(resId: Int) {
    resizeLengthByResource(resId)
    var uri = UriUtil.getUriForResourceId(resId)
    controller = Fresco.newDraweeControllerBuilder().setAutoPlayAnimations(true).setUri(uri).build();
}

/**
 * 宽度固定,高度等比缩放
 */
fun ImageView.resizeLengthByResource(resId: Int) {
    try {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(resources, resId, options)
        // 需要post才能获取高度,不然options.outWidth为0
        post {
            val ratio = width.toFloat() / options.outWidth
            val newHeight = ratio * options.outHeight
            val newLayoutParams = layoutParams
            newLayoutParams.height = newHeight.toInt()
            layoutParams = newLayoutParams
            Log.dMulti("loadLocalImage", ratio.toString(), options.outWidth.toString(), options.outHeight.toString(), width.toString(), newHeight.toString())
        }
    } catch (e: Exception) {
        e?.printStackTrace()
        Log.dMulti("loadLocalImage exception", e?.message)
    }
}
上一篇下一篇

猜你喜欢

热点阅读