【问题标题】:Adding Image to 2d Game in Android?在 Android 中将图像添加到 2d 游戏?
【发布时间】:2014-02-23 12:01:19
【问题描述】:

我正在尝试将一个简单的 2d 图像(.png 格式)添加到我的 2d 游戏中。我的游戏由一个扩展表面视图的 Game View 类、一个控制游戏逻辑并绘制画布的 GameState 类和一个 Main 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

}

它负责绘制游戏中的所有对象。我可以很容易地画一个矩形。但我无法弄清楚如何将图像绘制到我的游戏中。我计划让图像动态移动(如精灵)。

如何在上述方法中绘制精灵?

我不能这样做:

bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

因为 GameState 没有扩展 View

谢谢

【问题讨论】:

    标签: java android canvas


    【解决方案1】:

    一个简单的解决方案是。

    • 首先您需要将图像存储在资产文件夹中
    • 那么你需要调用 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.drawBitmap(bitmap, x, y, paint);

      该方法的参数为: bitmap 要绘制的位图 x 正在绘制的位图左侧的位置 y 正在绘制的位图顶部的位置 paint 用于绘制位图的paint(通常为null)

    示例: canvas.drawBitmap(yourImage, 100, 100, null);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 2012-02-15
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多