簡體   English   中英

在運行時動態替換 Lottie 動畫中的 Image

[英]Dynamically replace Image in Lottie animation at runtime

我有一個 After Effects 動畫,超級簡單,一個正方形四處移動(AE 形狀)。 我使用 Bodymovin 將動畫導出為 .json,並在我的項目中使用 Lottie 添加 json 文件。 到現在為止還挺好。

問題從這里開始 --> 在運行時,用我在我的項目中也有的圖像替換那個“正方形”。 因為這個圖片可能會發生變化,我無法靜態添加到我的AE動畫中,所以需要在運行時動態添加。 幾乎沒有關於如何在 Android 中執行此操作的信息?

LottieAnimationView擴展了一個ImageView 換句話說, LottieAnimationView也是一個ImageView

因此,您可以像將圖像設置為ImageView一樣在LottieAnimationView上設置圖像

例如:

if (isAnimated) {
    mLottieView.setAnimation("<json file name from asset folder>");
} else {
    mLottieView.setImageResource(R.drawable.square_image);
}

這只是關於如何使用相同的視圖播放動畫(json 文件)或圖像的示例,就像任何ImageView ..

Lottie 有一個XML屬性app:lottie_imageAssetsFolder ,也可以在運行時設置: animationView.setImageAssetsFolder("images/"); . 使用該集合,您可以在json引用圖像。 這是在線記錄的; 請參閱第 # 599和 # 630行上方的注釋。 這也在文檔中進行了解釋( src/assets可能不是一個選項,因為它不可寫):

有時,您沒有將圖像與設備捆綁在一起。 您可以這樣做以節省 apk 中的空間,或者如果您從網絡下載動畫。 要處理這種情況,您可以在LottieAnimationViewLottieDrawable上設置ImageAssetDelegate 每次 Lottie 嘗試渲染圖像時都會調用該委托。 它將傳遞圖像名稱並要求您返回位圖。 如果您還沒有它(例如,如果它仍在下載),則只需返回 null,Lottie 將繼續詢問每一幀,直到您返回非空值。

animationView.setImageAssetDelegate(new ImageAssetDelegate() {
    @Override
    public Bitmap fetchBitmap(LottieImageAsset asset) {
        if (downloadedBitmap == null) {
            // We don't have it yet. Lottie will keep asking until we return a non-null bitmap.
           return null;
        }
        return downloadedBitmap;
    }
});

設法做到這一點:問題是我的 After Effects 動畫有一個矢量形狀,我試圖替換它。 在我將原始動畫更改為 .png 后,我可以在運行時替換圖像。 工作得很好。

// First I converted the png I wanted to see at runtime to a bitmap:

Bitmap bitmapImage = BitmapFactory.decodeResource(getResources(), R.drawable.imageBlah);

// I used the lambda: 

lottieAnimationView.setImageAssetDelegate( lottieImageAsset -> bitmapImage);

這適用於一個圖像,現在我將看看如何在運行時替換多個圖像。

這就是您如何將圖像動態加載到 lottie 中的方法。 在這個例子中,我通過 URL 加載。 您也可以類似地加載捆綁的圖像。

Glide.with(this)
            .asBitmap()
            .load(url)
            .into(object : CustomTarget<Bitmap>(){
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    lottie.addLottieOnCompositionLoadedListener {
                        val scaledBitmap = Bitmap.createScaledBitmap(resource, 282, 167, false)
                        lottie.updateBitmap("image_0", scaledBitmap)
                    }
                }
                override fun onLoadCleared(placeholder: Drawable?) {
                }
            })

image_0 是您要在“資產”對象下的 lottie json 中替換的圖像的 ID。

縮放位圖是可選的。

"assets": [{
    "id": "image_0",
    "w": 282,
    "h": 167,
    "u": ""}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM