簡體   English   中英

如何在畫布上繪制軌跡? (Android)

[英]How to draw onto Canvas leaving a trail? (Android)

我正在編寫游戲,現在我正在為在屏幕上上下移動的精靈設置動畫。 在屏幕上繪制精靈后,我試圖繪制一個永久的位圖來代替動畫精靈所在的位置,有點像一條小路。 但是,我不確定如何永久地將其繪制到Canvas上或將位圖保存到畫布上,以便在onDraw更新時它保持在屏幕上。 我希望在屏幕上向下移動的角色在他身后留下一條從位圖繪制的路徑。 有什么辦法嗎? 我正在Windows 7上使用具有Java的Android SDK(Eclipse)進行編程。

這個想法是讓角色及其蹤跡獨立計算:

基本解決方案

Path mCharacterPath=new Path();


public void onDraw(Canvas canvas) {

      canvas.drawBitmap (mCharacter, mPosX, mPosY, mCharacterPaint);
      canvas.drawPath (mCharacterPath, mPathPaint);

}

public void add_point_to_path(int x, int y) {
       mPath.lineTo(x,y);
}

所以每隔一段時間,您只需致電

add_point_to_path (mPosX, mPosY);

它將當前精靈位置添加到路徑。

正如您所猜測的那樣,更改mPathPaint可以自定義路徑的類型。 此外,您還可以添加圓弧,曲線等。

更好的解決方案

另一種解決方案是在所有內容下方創建一個透明的位圖:

public void onDraw(Canvas canvas) {


     // we draw our auxiliary bitmap that contains all the trails
     canvas.drawBitmap (mTransparentBitmapForTrails, 0, 0, mTransparentBitmapPaint);
     .
     // then we draw the usual stuff, characters, etc...
     canvas.drawBitmap (mCharacterBimap, mPosX, mPosY, mCharacterPaint);
     .
     .
} 

// this creates a transparent background the size of the screen
// you will render trails here and they all will be painted at once in onDraw below the craracters

Bitmap mBitmapForTrails;
Canvas mCanvasForTrails;

public void initializeBitmapForTrails() {
      mBitmapForTrails=new Bitmap(); // checkout how to create bitmaps with specific w&h, can't remember at the moment. 
      mCanvasForTrails=new Canvas(mBitmapForTrails); // we create a canvas to draw in that bitmap
}

// this will paint the trail in our secondary bitmap. This secondary bitmap doesn't get
// erased, so the drawTrail()'s are accumulative

public void drawTrail (int x, int y) {
   mCanvasForTrails.drawBitmap(your_cool_trail_bitmap, x, y, mTrailPaint);
   invalidate(); // this works, but for performance you'll later do invalidate(rect), so Android only repaints the changed portion of the bitmap. That rect will be the rectangle occupied by the trail bitmap. ie. (x,y,x+trailw,y+trialh)
}

因此您將繪制所有到該位圖的跡線。 這樣做的好處是路徑可能非常復雜,而根本不影響性能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM