主要课程是:
public class test extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new Game(this,null));
}
}
Game类是从view类扩展而来的,可以让我们绘制汽车并设置它的位置,我调用了onkey方法来控制汽车的方向和角度
public class Game extends View {
private Paint paint= new Paint();
float x,y;
float speed = 5,angle = 0,mod = 0;
Bitmap car;
Boolean b=false;
public Game(Context context, AttributeSet attrs) {
super(context, attrs);
try { // here I call the car image as a bitmap object
AssetManager assetManager=context.getAssets();
InputStream inputStream= assetManager.open("car.png");
BitmapFactory.Options options=new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_4444;
car=BitmapFactory.decodeStream(inputStream,null,options);
inputStream.close();
Log.d("Bitmap Text", "bobrgb888.png format: "+car.getConfig());
} catch (Exception e) {
// TODO: handle exception
}
}
@Override
protected void onDraw(Canvas canvas) {
x += (speed*mod) * Math.cos(Math.PI/180 * angle);
y += (speed*mod) * Math.sin(Math.PI/180 * angle);
canvas.rotate((float) (Math.PI/180 * angle));
canvas.drawBitmap(car,-(car.getWidth()/2), -(car.getHeight()/2), null);
canvas.restore();
}
public boolean onKey(View view, int keyCode, KeyEvent event) {
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
break;
case KeyEvent.ACTION_UP:
{if(event.getKeyCode() == KeyEvent.KEYCODE_A || event.getKeyCode() == KeyEvent.KEYCODE_B)
{
this.mod = 0;
}}
break;
case KeyEvent.ACTION_MULTIPLE:{
if(event.getKeyCode() == KeyEvent.KEYCODE_A)
{
mod = 1;
}
if(event.getKeyCode() == KeyEvent.KEYCODE_B)
{
mod = -1;
}
if(event.getKeyCode() == KeyEvent.KEYCODE_C)
{
angle -= 5;
}
if(event.getKeyCode() == KeyEvent.KEYCODE_D)
{
angle+=5;
}
}
break;
}
invalidate();
return event.getKeyCode() != KeyEvent.KEYCODE_BACK;
}
}
我设置下一个点的 x 和 y 我旋转图像,按照选择的角度在当前位置绘制汽车。当A键或B键向上时,长按(A、B、C、D)键,车停,角度和方向改变。