欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android 逐帧动画OOM的解决方法

程序员文章站 2022-03-16 16:15:21
...

项目中都会使用到动画,有时候会使用到逐帧动画,然后当帧数较多时,就会发生OOM的问题,网上有许多文字是提供一个工具类,解决这个方法。
关于这个工具类的使用的原文地址:http://blog.csdn.net/u014702999/article/details/50544455

效果图(图片是gif需要等待一下才可以使用):
Android 逐帧动画OOM的解决方法

这篇文章主要是换一种思路,如果我们只是需要动画每隔一段时间重复一次。那么我们仅使用gif图片进行展示就可以实现效果,下面提供一个我使用的GifView类,

内存由原来的180M降到了14M

package com.alpha.alphaapp.anim;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;

import com.alpha.alphaapp.R;

public class GifView extends View {

    /**
     * 默认为1秒
     */
    private static final int DEFAULT_MOVIE_DURATION = 1000;

    private int mMovieResourceId;

    private Movie mMovie;

    private long mMovieStart;
    //当前动画
    private int mCurrentAnimationTime = 0;

    private float mLeft;

    private float mTop;

    private float mScale;

    private int mMeasuredMovieWidth;

    private int mMeasuredMovieHeight;

    private boolean mVisible = true;

    private volatile boolean mPaused = false;

    public GifView(Context context) {
        this(context, null);
    }

    public GifView(Context context, AttributeSet attrs) {
        this(context, attrs, R.styleable.CustomTheme_gifViewStyle);
    }

    public GifView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setViewAttributes(context, attrs, defStyle);
    }

    @SuppressLint("NewApi")
    private void setViewAttributes(Context context, AttributeSet attrs,
                                   int defStyle) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        // 从描述文件中读出gif的值,创建出Movie实例  
        final TypedArray array = context.obtainStyledAttributes(attrs,
                R.styleable.GifView, defStyle, R.style.Widget_GifView);
        mMovieResourceId = array.getResourceId(R.styleable.GifView_gif, -1);
        mPaused = array.getBoolean(R.styleable.GifView_paused, false);
        array.recycle();
        if (mMovieResourceId != -1) {
            mMovie = Movie.decodeStream(getResources().openRawResource(
                    mMovieResourceId));
        }
    }

    /**
     * 设置gif图资源
     *
     * @param movieResId
     */
    public void setMovieResource(int movieResId) {
        this.mMovieResourceId = movieResId;
        mMovie = Movie.decodeStream(getResources().openRawResource(
                mMovieResourceId));
        requestLayout();
    }

    public void setMovie(Movie movie) {
        this.mMovie = movie;
        requestLayout();
    }

    /**
     * 这里会停在最后一帧
     */
    public void stop() {
        this.mPaused = true;
        //获取最后一帧,主要是为了让动画在设置暂停时停在最后一帧
        mCurrentAnimationTime = mMovie.duration();
        invalidate();
    }

    /**
     * 开始动画,重第一帧开始
     */
    public void start() {
        this.mPaused = false;
        //获取最后一帧,主要是为了让动画在设置暂停时停在最后一帧
        mCurrentAnimationTime = 0;
        invalidate();
        //开始动画

    }

    public Movie getMovie() {
        return mMovie;
    }

    public void setMovieTime(int time) {
        mCurrentAnimationTime = time;
        invalidate();
    }

    /**
     * 设置暂停
     *
     * @param paused
     */
    public void setPaused(boolean paused) {
        this.mPaused = paused;
        if (!paused) {
            mMovieStart = android.os.SystemClock.uptimeMillis() - mCurrentAnimationTime;
        }
        invalidate();
    }

    /**
     * 判断gif图是否停止了
     *
     * @return
     */
    public boolean isPaused() {
        return this.mPaused;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mMovie != null) {
            int movieWidth = mMovie.width();
            int movieHeight = mMovie.height();
            int maximumWidth = MeasureSpec.getSize(widthMeasureSpec);
            float scaleW = (float) movieWidth / (float) maximumWidth;
            mScale = 1f / scaleW;
            mMeasuredMovieWidth = maximumWidth;
            mMeasuredMovieHeight = (int) (movieHeight * mScale);
            setMeasuredDimension(mMeasuredMovieWidth, mMeasuredMovieHeight);
        } else {
            setMeasuredDimension(getSuggestedMinimumWidth(),
                    getSuggestedMinimumHeight());
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        mLeft = (getWidth() - mMeasuredMovieWidth) / 2f;
        mTop = (getHeight() - mMeasuredMovieHeight) / 2f;
        mVisible = getVisibility() == View.VISIBLE;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mMovie != null) {
            if (!mPaused) {
                updateAnimationTime();
                drawMovieFrame(canvas);
                invalidateView();
            } else {
                drawMovieFrame(canvas);
            }
        }
    }

    @SuppressLint("NewApi")
    private void invalidateView() {
        if (mVisible) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                postInvalidateOnAnimation();
            } else {
                invalidate();
            }
        }
    }

    private void updateAnimationTime() {
        long now = android.os.SystemClock.uptimeMillis();
        // 如果第一帧,记录起始时间  
        if (mMovieStart == 0) {
            mMovieStart = now;
        }
        // 取出动画的时长  
        int dur = mMovie.duration();
        if (dur == 0) {
            dur = DEFAULT_MOVIE_DURATION;
        }
        // 算出需要显示第几帧  
        mCurrentAnimationTime = (int) ((now - mMovieStart) % dur);
    }

    private void drawMovieFrame(Canvas canvas) {
        // 设置要显示的帧,绘制即可
        mMovie.setTime(mCurrentAnimationTime);
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        canvas.scale(mScale, mScale);
        mMovie.draw(canvas, mLeft / mScale, mTop / mScale);
        canvas.restore();
    }

    @SuppressLint("NewApi")
    @Override
    public void onScreenStateChanged(int screenState) {
        super.onScreenStateChanged(screenState);
        mVisible = screenState == SCREEN_STATE_ON;
        invalidateView();
    }

    @SuppressLint("NewApi")
    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        mVisible = visibility == View.VISIBLE;
        invalidateView();
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
        mVisible = visibility == View.VISIBLE;
        invalidateView();
    }

}  

这个类是在别人的博客中找到的,自己又进行一些简单的修改,实现的效果与我用逐帧动画实现的效果一样,但内存由原来的180M降到了14M,简直瞬间感觉app都跑的快了,

在res/attrs中添加如下代码:

   <!--gitView-->
    <declare-styleable name="GifView">
        <attr name="gif" format="reference" />
        <attr name="paused" format="boolean" />
    </declare-styleable>
    <declare-styleable name="CustomTheme">
        <attr name="gifViewStyle" format="reference" />
    </declare-styleable>

关于这类的使用如下,也是特别简单:
layout.xml

 <com.alpha.alphaapp.anim.GifView
   android:id="@+id/login_iv_sheep"
   android:layout_width="147.5dp"
   android:enabled="false"
   android:layout_height="match_parent"
/>

MainActvity中的使用

R.raw.animation_sheep_normalR.raw.animation_super_normal就是放置到res/raw的gif图片资源

   gif_sheep = (GifView) findViewById(R.id.login_iv_sheep);
   gif_super = (GifView) findViewById(R.id.login_iv_super);
     gif_sheep.setMovieResource(R.raw.animation_sheep_normal);
    gif_super.setMovieResource(R.raw.animation_super_normal);
        isStop = false;
        //每隔三秒开始播放动画
        runnable = new Runnable() {
            @Override
            public void run() {
                //动画
                gif_sheep.setPaused(isStop);
                gif_super.setPaused(isStop);
                isStop=!isStop;
                handler.postDelayed(this, 3000);
            }
        };
        handler.postDelayed(runnable, 0);

Stop动画

  public void stopNormalAnim() {
        gif_sheep.stop();
        gif_super.stop();
        handler.removeCallbacks(runnable);
    }

onDestroy
最后在onDestroy中暂停动画

ifnull!=gif_super)
  gif_super.setPaused(true);

这篇文章的题目有点与内容不符,但是我们在开发中,不就是实现了效果为主么,实现方式尽可能的简化。希望对大家有帮助。