1

我正在开发一个带有 Lottie 动画的应用程序。抽签动画之一需要两个图像文件(img_0.png,img1_.png)。

例如,

lottie json file [ data.json ] : {"v":"5.1.7","fr":60,"ip":0,"op":120,"w":180,"h":200,"nm":"2","ddd":0,"assets":[{"id":"image_0","w":96,"h":96,"u":"images/","p":"img_0.png"},{"id":"image_1","w":180,"h":180,"u":"images/","p":"img_1.png"}],....

我无法在 main/assets 文件夹中为 LottieAnimationView 准备所有图像,因此我使用“setImageAssetDelegate”方法从 URL 异步获取多个图像。

这是我的代码:

        Glide.with(this)
            .asBitmap()
            .load("https://www.google.co.kr/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png")
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(final Bitmap resource, Transition<? super Bitmap> transition) {

                    LottieAnimationView lottie = findViewById(R.id.lottie);
                    lottie.setImageAssetDelegate(new ImageAssetDelegate() {
                        @Override
                        public Bitmap fetchBitmap(LottieImageAsset asset) {
                            return resource;
                        }
                    });
                    lottie.playAnimation();
                }
            });

但是如果我使用“setImageAssetDelegate”方法,我只能将一张图像放到 Lottie。我想在一个 Lottie 动画中放置多个不同的图像。

不像这样

我不想要这个。(上面的代码显示了这个动画)。

但像这样

我需要使用“setImageAssetDelegate”方法。

有人对此有任何想法吗?

4

2 回答 2

2

异步获取图像将不起作用。ImageAssetDelegate旨在成为动画播放时所需图像的“提供者” 。

它的方法public Bitmap fetchBitmap(LottieImageAsset asset)将在动画播放时为动画中的每个图像调用,您有责任提供正确的方法,其中传递给该方法的LottieImageAsset将为您提供当时需要哪个图像的详细信息,取自动画json文件。

您可以使用Glide来获取这些图像,但需要记住,您必须同步获取它们,并且在您加载/提供该图像之前,动画不会继续播放。

一个例子:

LottieAnimationView lottie = findViewById(R.id.lottie);
lottie.setImageAssetDelegate(new ImageAssetDelegate() {
    @Override
    public Bitmap fetchBitmap(LottieImageAsset asset) {
        return Glide.loadSychronous("http://" + asset.getId + ".png");
    }
});
lottie.playAnimation(); 

注意:这是伪代码,您必须查看如何同步加载图像,Glide并且您必须想出一种方法将图像 id 与正确的图像 url 匹配。

另一种方法Glide是加载动画所需的所有图像,保存它们(在内存或外部存储中),然后才开始播放动画;这可能适用于小动画;对于任何更大的东西,你都会遇到麻烦,因为 a. 所有图像的加载时间过长或 b。你内存不足。

于 2018-04-20T06:52:25.410 回答
1

这就是您可以动态地将图像加载到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 是要在“assets”对象下的 lottie json 中替换的图像的 id。您也可以对 image_1 类似地重复此过程。

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

缩放位图是可选的。

于 2021-11-10T15:57:16.020 回答