Set Animated .GIF As Background Android

前端 未结 3 701
借酒劲吻你
借酒劲吻你 2020-12-01 05:04

I am new to Android and I am having trouble playing an animated .gif file in the background of my layout. When I run the application the background is a single frame of the

相关标签:
3条回答
  • 2020-12-01 05:11

    As Martin says, Android does not support GIFs. As a workaround, Android offers Animation List/AnimationDrawable. You will need to convert the GIF into individual frames [.png files]. I use GIMP for the conversion

    Original GIF image

    This GIF can be broken down into its frames:

    GIF frames in GIMP

    Save them as frame01.png, frame02.png, and so on, and create an animation-list XML file, say, progress_animation.xml

    <animation-list android:id="@+id/selected" android:oneshot="false">
    <item android:drawable="@drawable/frame01" android:duration="50" />
    <item android:drawable="@drawable/frame02" android:duration="50" />
    <item android:drawable="@drawable/frame03" android:duration="50" />
    ....
    <item android:drawable="@drawable/frameN" android:duration="50" />
    

    To begin the animation, you need to cast the image to an AnimationDrawable, and call start() on it

    AnimationDrawable progressAnimation = (AnimationDrawable) yourImageView.getBackground();
    progressAnimation.start();
    
    0 讨论(0)
  • 2020-12-01 05:11

    The gif animation is supported in Android when GIF animation is played as Movie.

    Take a look.

    0 讨论(0)
  • 2020-12-01 05:34

    put your gif image in app\src\main\assets

    make a class like

    public class MyGifView extends View {
    Movie movie;
    InputStream is;
    long startTime;
    
    public MyGifView(Context context) {
        super(context);
        try {
            is = getResources().getAssets().open("anim.gif");
            movie = Movie.decodeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.WHITE);
        super.onDraw(canvas);
        long now = System.currentTimeMillis();
        if (startTime == 0) // first time
            startTime = now;
        int relTime = (int) ((now - startTime) % movie.duration());
        movie.setTime(relTime);
        float scalefactorx = (float) this.getWidth() / (float) movie.width();
        float scalefactory = (float) this.getHeight() / (float) movie.height();
        canvas.scale(scalefactorx,1);
        movie.draw(canvas, scalefactorx, scalefactory);
        this.invalidate();
    }
    

    }

    add a layout somewhere in your xml activity_layout (backgroundFrameLayout). Usage in your activity onCreate():

    FrameLayout frameLayout = findViewById(R.id.backgroundFrameLayout);
    frameLayout.addView(new MyGifView(this));
    
    0 讨论(0)
提交回复
热议问题