0

我试图让图像移动。图像不动,有时会闪烁。我想让它可运行。它使用一个 Surface Holder,s 是位图。画布有时保持静止在 i=0 或闪烁。如何使其可运行

package com.smiley;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class SmileyView extends SurfaceView implements SurfaceHolder.Callback {
    public SmileyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        holder = getHolder();
         s= BitmapFactory.decodeResource(context.getResources(),R.drawable.smiley);
         holder.addCallback(this);
    }

    @Override
public boolean onKeyUp(int keyCode, KeyEvent msg) {
    super.onKeyUp(keyCode, msg);

    rv.update();

    return true;
    }
private int i=0;
    private Bitmap s;private SurfaceHolder holder;private RenderView rv ;
     boolean grun=true;long t=0;
    public void resume()
    {
        rv=new RenderView();
    }


    @Override
    public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceCreated(SurfaceHolder arg0) {
        // TODO Auto-generated method stub
        grun=true;
        if(rv!=null)
        rv.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder arg0) {
        // TODO Auto-generated method stub
    try {
        grun =false;
        rv.join();
        rv=null;
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }


class RenderView extends Thread  {

    RenderView(){
    super();

    }
    @Override
    public void run()
    {
        SurfaceHolder h=holder;
        while(grun)
        {
            Canvas ca=null;
            try{ca = h.lockCanvas(null);
               synchronized (h) {
            update();   dodraw(ca);
               }
            }
            finally
            {
                if(ca!=null)
                h.unlockCanvasAndPost(ca);
            }
        }
    }
    public void dodraw(Canvas canvas)
    {   canvas.drawBitmap(s, i, i , null);

        canvas.restore();
    }
    public void update()
    {  
        if(i==0)
                  i=100;
    }
}
}
4

1 回答 1

0

我为您在这里想要做的事情做了一个教程。你可以在这里查看。如果我不得不猜测,那么可能是没有清理画布的问题。尝试将其更改为(假设您的背景是位图 backBG)

public void dodraw(Canvas canvas)
    {   
        canvas.drawBitmap(backBG, 0, 0, null);
        canvas.drawBitmap(s, i, i , null);

        canvas.restore();
    }
于 2012-04-30T11:38:20.357 回答