[英]Adding Image to 2d Game in Android?
我想在我的2D游戲中添加一個簡單的2D圖像(.png格式)。 我的游戲包括一個擴展表面視圖的游戲視圖類,一個控制游戲邏輯的GameState類,並繪制畫布和主要活動。 我的GameState類有這個方法:
// the draw method
public void draw(Canvas canvas, Paint paint) {
// Clear the screen
canvas.drawRGB(20, 20, 20);
// set the colour
paint.setARGB(200, 0, 200, 0);
// // draw the bats
// canvas.drawRect(new Rect(_bottomBatX, _bottomBatY, _bottomBatX
// + _batLength, _bottomBatY + _batHeight), paint); // bottom bat
}
它負責繪制游戲中的所有對象。 我可以輕松地繪制一個矩形。 但我無法弄清楚如何將圖像繪制到我的游戲中。 我計划動態移動圖像(像精靈一樣)。
如何在上面的方法中繪制一個精靈?
我不能這樣做:
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
因為GameState不擴展View
謝謝
一個簡單的解決方案就是。
然后,您需要調用AssetManager來獲取資產文件夾中的資產
Bitmap yourImage; AssetManager assetManager = context.getAssets();
獲取圖像的字節流
InputStream inputStream; inputStream = assetManager.open("yourImage.png"); // path is relative to the assets folder
讓BitmapFactory在解碼它並將其存儲到Bitmap類型的yourImage變量中
yourImage = BitmapFactory.decodeStream(inputStream); inputStream.close();
那么你需要在canvas對象中調用一個方法
canvas.drawBitmap(bitmap, x, y, paint);
該方法的參數是:位圖要繪制的位圖x正在繪制的位圖左側的位置y正在繪制的位圖頂面的位置繪制用於繪制位圖的繪制(通常這是null )
示例: canvas.drawBitmap(yourImage, 100, 100, null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.