过年了带你一起看烟花之动图加载

353 阅读1分钟

PK创意闹新春,我正在参加「春节创意投稿大赛」,详情请看:春节创意投稿大赛

背景

以前毎到过年的时候,最期待的几件事:压岁钱,放烟花,年夜饭

随着禁放烟花的实施,看自己燃放烟花和看烟花也愈发困难了,今天就为各位xdm带来了一场烟花秀,可以在手机上控制实时停止

  • 线上烟花

Kapture 2022-02-04 at 23.21.10.gif

实现

本文是通过AnimatedImageDrawable来实现动图加载

xml

在布局文件中使用ImageView作为动图的载体

<ImageView
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

代码

  • 首先获取到控件的对象
ImageView image = findViewById(R.id.image);
  • 从资源里加载git图片对象
Drawable drawable = ImageDecoder.decodeDrawable(
        ImageDecoder.createSource(getResources(), R.drawable.demo));

由于git可能比较大,属于耗时资源,所以需要在子线程中获取,获取到git图片对象后并将对象设置给ImageView控件,同时开启动画

new Thread(() -> {
    try {
        Drawable drawable = ImageDecoder.decodeDrawable(
                ImageDecoder.createSource(getResources(), R.drawable.demo));
        image.setImageDrawable(drawable);
        if (drawable instanceof AnimatedImageDrawable) {
            // Prior to start(), the first frame is displayed.
            /*设置重复次数*/
            ((AnimatedImageDrawable)drawable).setRepeatCount(1);
            ((AnimatedImageDrawable)drawable).start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}).start();
  • 手动控制git动画的开启和停止

增加两个按钮,来控制动画的开启和停止

<Button
    android:id="@+id/start"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:text="开启动画"
    android:layout_width="wrap_content"
    android:layout_height="50dp"/>
<Button
    android:id="@+id/stop"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/start"
    android:text="关闭动画"
    android:layout_width="wrap_content"
    android:layout_height="50dp"/>
  • 通过AnimatedImageDrawable中的方法控制动画的开启和停止

开启动画

start.setOnClickListener(v -> {
    if (drawable instanceof AnimatedImageDrawable) {
        // Prior to start(), the first frame is displayed.
        /*设置重复次数*/
        ((AnimatedImageDrawable)drawable).setRepeatCount(100);
        ((AnimatedImageDrawable)drawable).start();
    }
});

结束动画

stop.setOnClickListener(v -> {
    if (drawable instanceof AnimatedImageDrawable) {
        ((AnimatedImageDrawable)drawable).stop();
    }
});

常用方法

isRunning:返回当前动画是否在运行
setRepeatCount:指定动画重复的次数
start:开启动画
stop:停止动画

最后祝各位xdm 虎年大吉,身体健康,心想事成,万事如意!