我正在尝试向我的 2d 游戏中添加一个简单的 2d 图像(.png 格式)。我的游戏包含一个扩展表面 View 的游戏 View 类、一个控制游戏逻辑并绘制 Canvas 的 GameState 类和一个主 Activity 。我的 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
}
它负责绘制游戏上的所有对象。我可以很容易地画出一个矩形。但我无法弄清楚如何将图像绘制到我的游戏中。我计划让图像动态移动(如 Sprite )。
如何在上述方法中绘制 Sprite ?
我不能这样做:
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
因为 GameState 不扩展 View
谢谢
最佳答案
一个简单的解决方案是。
- 首先您需要将图像存储在 Assets 文件夹中
然后你需要调用AssetManager来获取你的assets文件夹中的assets
位图你的图像; AssetManager assetManager = context.getAssets();
获取图片的字节流
输入流输入流; inputStream = assetManager.open("yourImage.png"); //路径是相对于 Assets 文件夹的
让 BitmapFactory 进行解码并将其存储到 Bitmap 类型的 yourImage 变量中
yourImage = BitmapFactory.decodeStream(inputStream); inputStream.close();
然后你需要在 Canvas 对象中调用一个方法
canvas.drawBitmap(bitmap, x, y, paint);
该方法的参数为: bitmap 要绘制的位图 x 正在绘制的位图左侧的位置 y 正在绘制的位图顶边的位置 paint 用于绘制位图的paint(通常为null)
例子:
canvas.drawBitmap(yourImage, 100, 100, null);
关于java - 在 Android 中将图像添加到 2d 游戏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21967918/