Set Animated .GIF As Background Android

前端 未结 3 784
借酒劲吻你
借酒劲吻你 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: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));
    

提交回复
热议问题