ouhz_rM
ouhz_rM
采纳率0%
2016-06-15 13:19 阅读 1.6k

做个打小飞机游戏的bug,关于图片移动的问题,有时候移动图片移动多次会卡死,不动了,如何解决?

1

public class PlaneView extends View {

public float currentX;
public float currentY;
private final Bitmap mBitmap_plane;

public PlaneView(Context context) {
    super(context);
    //将图片转换成Bitmap形式
    mBitmap_plane = BitmapFactory.decodeResource(context.getResources(), R.drawable.plane);
    //设置焦点
    setFocusable(true);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    //创建画笔
    Paint p = new Paint();

    //在画布上画一张图片
    canvas.drawBitmap(mBitmap_plane,currentX,currentY,p);
}

}

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

private int speed = 10;
private PlaneView mPv;
private myOnKeyListener listener = null;
private ImageView mImageView;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    //全屏显示

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    mPv = new PlaneView(this);
    setContentView(mPv);

    mPv.setBackgroundResource(R.color.colorPrimary);

    //获取窗口管理器
    WindowManager windowManager = getWindowManager();
    Display defaultDisplay = windowManager.getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();

    //获取屏幕的宽高
    defaultDisplay.getMetrics(metrics);

    //设置飞机的初始位置
    mPv.currentX = metrics.widthPixels / 2;
    mPv.currentY = metrics.heightPixels - 40;
    mPv.setOnKeyListener(listener == null ? new myOnKeyListener() : listener);
}


class myOnKeyListener implements View.OnKeyListener {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_S:
                mPv.currentY += speed;
                break;

            case KeyEvent.KEYCODE_W:
                mPv.currentY -= speed;
                break;

            case KeyEvent.KEYCODE_A:
                mPv.currentX -= speed;
                break;

            case KeyEvent.KEYCODE_D:
                mPv.currentX += speed;
                break;
        }
        mPv.invalidate();
        return true;
    }
}

}

当移动多次就卡死不动了,LogCat也没有打印日志,我的开发环境是AS2.1

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • qq_34544496 练小芽 2016-06-16 02:25

    我觉得可能有两个原因,一个是可能你给的图片有点大,无论是绘制什么的有点慢,另一个我觉得你不该Paint p = new Paint();放在onDraw()里边,频繁得创建对象和回收对象是很耗内存的,gc回收时运行在主线程,一旦时间过长就会造成很大的卡顿

    点赞 评论 复制链接分享
  • a332324956 程序员入门进阶 2016-06-16 05:54

    使用libgdx引擎,要在gpu下面去绘制,否则肯定卡顿

    点赞 评论 复制链接分享

相关推荐