2013-06-11 173 views
0

我是新來的android編程,並遇到一個小問題。如果你能幫忙,那將不勝感激。繪製矩形畫布android

我提出長方形的動態壁紙我使用製作:

void drawFrame() { 
     final SurfaceHolder holder = getSurfaceHolder(); 

     Canvas c = null; 
     try { 
      c = holder.lockCanvas(); 
      if (c != null) { 
       Paint paint = new Paint(); 
       paint.setColor(Color.CYAN); 
       Paint ypaint = new Paint(); 
       ypaint.setColor(Color.RED); 
       Paint ppaint = new Paint(); 
       ppaint.setColor(Color.GREEN); 

       drawVerStripes(c, ppaint, 0,20); 
       drawVerStripes(c, paint, 50,20); 
       drawVerStripes(c, ypaint,0,10); 
      } 

     } finally { 
      if (c != null) 
       holder.unlockCanvasAndPost(c); 
     } 

功能:

PARAMS:
寬度:矩形的寬度
空間:之間的區別最後一個和這個矩形

int y=0; 
    int oldY=0; 
    private void drawVerStripes(Canvas c, Paint paint, int space, int width) { 


     y=oldY+space; 

     c.drawRect(y, 0, y+width,c.getHeight(), paint); 

     oldY=y; 
    } 

結果是矩形很快移動到屏幕的一側。我希望他們留在屏幕上,並且不能移動
換句話說,有沒有一種方法drawVerStripes只執行一次而不是每一幀。

+0

你的問題是什麼? – Raghunandan

回答

0

您的drawFrame方法在每幀中調用。如果你的設備刷新率是70,那麼你的方法被稱爲每秒70次。如果將x或y座標增加1,則在x或y座標中移動70個像素。你應該做刷新率獨立運動。

1)計算增量時間,即自上次屏幕更新後經過的時間。 2)確定你想讓矩形每秒移動多少個像素。

假設你想讓你的矩形在x中移動50個像素。

然後執行以下操作。 x + = deltaTime * 50.

long startTime = System.nanoTime(); // Execute before the first time your drawFrame executes 
float deltaTime = (System.nanoTime()-startTime)/1000000000.0f; // In drawFrame method calculate 
long startTime = System.nanoTime(); // Execute after calculating delta time. 
+0

其實,我不想讓它移動...... –

+0

然後只需要一個叫做ranOnce的布爾變量。然後將其設置爲false。並在if(!ranOnce)中打包調用drawVerStripes。另外在調用drawVerStripes之後,設置了ranOnce = true – neo

+0

不知道爲什麼,但是在做完之後,rects不顯示出來......'boolean ranOnce = false; \t如果(ranOnce!){ \t \t \t \t \t drawVerStripes(C,ppaint,0,20); \t \t \t \t \t drawVerStripes(c,paint,50,20); \t \t \t \t \t drawVerStripes(c,ypaint,0,10); \t \t \t \t \t ranOnce = true; \t \t \t \t \t}' –

0

我相信你需要在drawFrame的開頭再次設置y和oldY爲0。