Android port of Box2d
作者: 刘鹏
日期: 2009-03-23
本文介绍了移植 Box2D 到 Android 的过程,给出了具体的移植方法和设计思路。
简介
将 Box2D 移植到 Android 上。Android 的 SDK 是基于 Java 的。
JBox2D 已经将 Box2D 移植到 Java 了,但在图形方面,它采用了 Processing 库,我们需要做的就是将 JBox2D 的图形渲染部分在 Android 上实现。
JBox2D 分析
![]() |
JBox2D Testbed 类图 |
设计
所有的绘制都在一个 View 中完成,我们需要设计一个 View,它从 Android 的 View 类继承而来,在 onDraw 函数中完成绘制操作;
DebugDraw 是图形渲染的基类,不必修改。我们要做的主要是实现 DebugDraw 的一个子类,用 Android SDK 来实现从 DebugDraw 继承来的绘制接口。
在 AndroidDebugDraw 中实现放一个 mBitmap ,AndroidDebugDraw 先绘制到 Bitmap 上,在 View 中将该 Bitmap 贴到屏幕上。
public void onDraw(Canvas canvas) {
/* Get bitmap object of AndroidDebugDraw*/
Bitmap bmp = ((AndroidDebugDraw)g).mBitmap;
/* Erase backgroud. */
bmp.eraseColor(0);
/* Step and draw the word */
currentTest.step ();
/* Paint AndroidDebugDraw's bimtap to view */
canvas.drawBitmap (bmp, 0, 0, myPaint);
/* repaint the screen */
invalidate ();
}
设计类图如下所示:
屏幕截图