【问题标题】:Android simple game. Add imagebuttons on game-view安卓简单游戏。在游戏视图上添加图像按钮
【发布时间】:2016-09-16 13:02:09
【问题描述】:

是否可以将按钮/图像按钮放在“游戏表面”之上? 我正在尝试使用此博客中的代码: https://www.simplifiedcoding.net/android-game-development-tutorial-1/

我需要用一些按钮改变屏幕上对象的方向。 在教程中,如果在任何地方按下触摸屏,船就会改变方向。

我试过这个: ImageButton b1 = (ImageButton) findViewById(R.id.turn_left); 为了稍后使用 addView 将按钮添加到视图中,但它返回 null。 也许是因为 setContentView(gameView);设置 GameView 的视图而不是 游戏活动? 关于如何使这项工作的任何建议?

public class GameActivity extends AppCompatActivity  {

    private GameView gameView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Getting display object
    Display display = getWindowManager().getDefaultDisplay();

    //Getting the screen resolution into point object
    Point size = new Point();
    display.getSize(size);

    gameView = new GameView(this, size.x, size.y);

    //adding it to contentview
    setContentView(gameView);
}

游戏视图

public class GameView extends SurfaceView implements Runnable { 
     ...code...
     private void draw() {

    //checking if surface is valid
    if (surfaceHolder.getSurface().isValid()) {
        //locking the canvas
        canvas = surfaceHolder.lockCanvas();
        //drawing a background color for canvas
        canvas.drawColor(Color.BLACK);
        //Drawing the player
        canvas.drawBitmap(
                ...code...
                draw);
        //Unlocking the canvas
        surfaceHolder.unlockCanvasAndPost(canvas);
    }
}
....code....
 @Override
public boolean onTouchEvent(MotionEvent motionEvent) {
    switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_UP:
         ...code...
    return true;
    }
}

XML

xmlns:tools="http://schemas.android.com/tools"
tools:context="package.GameActivity">

<ImageButton
    android:id="@+id/turn_left"
    android:background="@drawable/left"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

【问题讨论】:

    标签: java android


    【解决方案1】:

    您可以创建通过画布绘制位图的自定义按钮类。

    【讨论】:

    • 谢谢,但我不确定您所说的“通过画布绘制位图”是什么意思?
    • 使用 canvas.drawBitmap(bitmapPressed,rect); 创建有两个位图按下和未按下按钮并在触摸按下时绘制的类并在修饰后未按下 draw canvas.drawBitmap(bitmapunPressed,rect);
    猜你喜欢
    • 2017-01-07
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多