Android-使用SurfaceView是非常滞后的

时间:2014-07-26 06:28:15

标签: android bitmap

在我的应用程序中,我有一个简单的动画,其中一个小位图在屏幕上移动。我使用了一个表面视图来实现这一点,但是位图移动非常轻松,或者在某些模拟设备上根本没有移动。从我的理解,这可能是因为在UI线程上运行的所有内容,但是在按照一个例子后,我相信我使用了两个线程(不是100%肯定)我试过调查Asynctasks来解决这个问题,但似乎无法弄清楚如何将它应用到我拥有的东西上。

这是我的代码:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;

public class MySurface extends SurfaceView implements Runnable {


SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = true;

Bitmap background;
Bitmap clouda;


float cloudax;


public MySurface(Context context) {
    super(context);
    init(context);

}

public MySurface(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

public MySurface(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context);
}

private void init(Context context) {
    // do stuff that was in your original constructor...
    ourHolder = getHolder();
    ourThread = new Thread(this);
    ourThread.start();


    DisplayMetrics metrics = new DisplayMetrics();
    WindowManager windowManager = (WindowManager)   context.getSystemService(Context.WINDOW_SERVICE);
    windowManager.getDefaultDisplay().getMetrics(metrics);

    int screenHeight = metrics.heightPixels;
    int screenWidth = metrics.widthPixels;

    background = BitmapFactory.decodeResource(getResources(), R.drawable.island);
    clouda = BitmapFactory.decodeResource(getResources(), R.drawable.clouda);

    cloudax = screenWidth;

}


public void pause(){
    isRunning = false;
    ourThread.interrupt();
    ourThread = null;
}

public void resume(){
    isRunning = true;

}


public void run() {
    // TODO Auto-generated method stub
    while(isRunning){
        if (!ourHolder.getSurface().isValid())
            continue;



        Canvas canvas = ourHolder.lockCanvas(); 


        Rect drawableRect = new Rect(0, 0, background.getWidth(), background.getHeight());
        RectF viewRect = new RectF(0, 0, getWidth(), getHeight());


        canvas.drawBitmap(background, drawableRect, viewRect, null);
        canvas.drawBitmap(clouda, cloudax, (getWidth()/2), null);

        if (cloudax > -276) {
            cloudax -= 10;
        }else{
            cloudax = getWidth();
        }

        ourHolder.unlockCanvasAndPost(canvas);

      }

  }




}

0 个答案:

没有答案