2012-04-30 149 views
0

我試圖讓圖像移動。圖像不會移動,有時會閃爍。 我想讓它成爲Runnable。它使用曲面支架,s是位圖。畫布有時會保持在i = 0或閃爍。如何使它可運行畫布佈局與SurfaceView

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; 
    } 
} 
} 

回答

0

我做了一個教程,看看你想在這裏做什麼。你可以看看here。如果我不得不猜測,那麼不清除畫布可能是一個問題。嘗試將其更改爲(假設你的背景是位圖backBG)

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

     canvas.restore(); 
    } 
+0

如果背景是位圖,然後 – user1318755

+0

嘗試編輯答案轉出backBG作爲背景 – MikeIsrael

+0

的名字,現在我想改變我的由值關鍵方法。但是當我按下按鈕的位置不會改變。我也使用了canvas.drawcolor。 – user1318755