Show .gif with android.graphics.Movie

2020-05-19 00:06发布

I'm trying, create a view with an animated GIF..

When i try run the follow code in emulator all works fine. But when i try run in real Smart Phone, nothing happens..

My view:

public class GIFView extends View {

private Movie mMovie;
private long movieStart;

public GIFView(Context context) {
    super(context);
    initializeView();
}

public GIFView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initializeView();
}

public GIFView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    initializeView();
}

private void initializeView() {
    InputStream is = getContext().getResources().openRawResource(
            R.drawable.cookies2);
    mMovie = Movie.decodeStream(is);
}

protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.TRANSPARENT);
    super.onDraw(canvas);
    long now = android.os.SystemClock.uptimeMillis();

    if (movieStart == 0) {
        movieStart = (int) now;
    }
    if (mMovie != null) {
        int relTime = (int) ((now - movieStart) % mMovie.duration());
        mMovie.setTime(relTime);
        mMovie.draw(canvas, getWidth() - mMovie.width(), getHeight()
                - mMovie.height());
        this.invalidate();
    }
}}

My activity:

public class MainActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     GIFView gifView = new GIFView(this);
     setContentView(gifView);
}}

My Smartphone screenshot: My Smartphone screenshot My emulator screenshot: My emulator screenshot

Why my app doesn't run in smartphone?

3条回答
【Aperson】
2楼-- · 2020-05-19 00:43

I dont think the Movie object works correctly on devices where hardware acceleration is turned on (which is turned on by default in Android 4.x for devices that support it. Your emulator may not.)

Try adding

 android:hardwareAccelerated="false"

to the activity definition for MainActivity in AndroidManifest.xml

Example:

<activity
    android:name=".MainActivity"
    android:hardwareAccelerated="false"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
查看更多
forever°为你锁心
3楼-- · 2020-05-19 00:50

Don't turn off hardware acceleration for the whole application. That's crippling. Just turn it off for the view:

setLayerType(View.LAYER_TYPE_SOFTWARE, null);
查看更多
霸刀☆藐视天下
4楼-- · 2020-05-19 01:01

Loading an animated GIF seems tricky, but I would suggest to use a WebView as an alternative.

Do as follow to resolve the problem :

  1. Copy your GIF in Android Assets.
  2. Call webView.loadDataWithBaseURL("file:///android_asset/", "", "text/html", "utf-8", null);

I hope it helps !

查看更多
登录 后发表回答