循环

时间:2016-06-04 10:19:37

标签: android multithreading image canvas

我是Android新手,我需要创建一个图像地图,即我在位图中有一个自定义地图,我需要在图像地图上显示和移动光标(位置指示器)。我使用Image View来显示图像和画布,将光标绘制在该图像上,这在以下代码中工作正常:

WalMap = BitmapFactory.decodeResource(getResources(), R.drawable.map);
bMap = Bitmap.createBitmap(WalMap.getWidth(), WalMap.getHeight(), Bitmap.Config.RGB_565);
canvas = new Canvas(bMap);
canvas.drawBitmap(WalMap, 0, 0, null);
icon = BitmapFactory.decodeResource(getResources(), R.drawable.cursor);
icon = Bitmap.createScaledBitmap(icon, 30, 30, false);
canvas.drawBitmap(icon, 90, 100, paint);
image.setImageDrawable(new BitmapDrawable(getResources(), bMap));

现在,我需要每隔X秒说一次刷新光标的位置。当我尝试在循环或线程中执行此操作时,应用程序会在我的手机上强制关闭。以下是使用线程的尝试:

    Thread thread = new Thread() {
    @Override
    public void run() {
        try {
            doMySearch(width,height,move,canvas);
            while (true) {
                sleep(1000);
                break;
            }
            move=100;
            doMySearch(width,height,move,canvas);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } };    public void doMySearch(int xaxis, int yaxis, int ymove,Canvas canvas) {

            canvas.drawBitmap(icon, xaxis / 2 + 90, yaxis / 3 + ymove + i, paint);
            image.setImageDrawable(new BitmapDrawable(getResources(), bMap));
    }

此外,如果我在循环中尝试此操作,画布仍然会将光标的先前位置保留在显示器上,并且在重绘时不会刷新。将不胜感激任何帮助。感谢。

1 个答案:

答案 0 :(得分:0)

更新线上的用户界面

Thread t = new Thread() {

@Override
public void run() {
try {
  while (!isInterrupted()) {
    Thread.sleep(1000);
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        doMySearch();
      }
    });
  }
} catch (InterruptedException e) {
}
}
};

t.start();

更新您的位置

//Create a new image bitmap and attach a brand new canvas to it
drawBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),     Bitmap.Config.RGB_565);
uLocationCanvas = new Canvas(drawBitmap);

uLocationCanvas.drawBitmap(bitmap, 0, 0, null);

uLocationPaint = new Paint();
uLocationPaint.setColor(Color.BLUE);

bitmapDrawable = new BitmapDrawable(getResources(), drawBitmap);

//Draw the image bitmap into the cavas
uLocationCanvas.drawBitmap(bitmap, 0, 0, null);

uLocationPaint = new Paint();
uLocationPaint.setColor(Color.BLUE);
//Draw everything else you want into the canvas, in this example a rectangle  with rounded edges
uLocationCanvas.drawCircle(x, y, 10, uLocationPaint);

//Attach the canvas to the ImageView
floorImage.setImageDrawable(new BitmapDrawable(getResources(), drawBitmap));


hope this will help