0

我正在尝试做一个简单的应用程序,每 500 毫秒更改一次画布背景颜色,在画布上我想创建 n 个圆圈,每个圆圈每 x 毫秒改变一次半径。

如果我在“run()”方法中的睡眠时间是由卡瓦斯颜色变化决定的,我该怎么做。我应该为每个圈子创建一个新线程并同步所有圈子吗?

显然,我还需要考虑到必须在画布背景颜色更改后绘制圆圈,因为我会冒着由于在圆圈上方绘制背景层而导致圆圈不可见的风险?

对于这种工作,我应该考虑使用 opengl 吗?

这是我的运行():

public void run() {
            int i=0;
            Paint paint= new Paint();
            paint.setColor(Color.RED);

            Log.d("ZR", "in running");
            while(running){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if(!holder.getSurface().isValid())
                    continue;
                Canvas canvas = holder.lockCanvas();
                canvas.drawRGB(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
                canvas.drawCircle(canvas.getWidth()/2, canvas.getHeight()/2, 100, paint);
                holder.unlockCanvasAndPost(canvas);
                Log.d("ZR", "in running: "+i +" count: "+j);
                i++;
                j++;
            }
        }
4

1 回答 1

1

An alternative to using Thread.sleep() would be to implement a timer to trigger your different drawing routines. Here is some pseudocode:

timeOfLastBackgroundChange = currentSystemTime()
timeOfLastCircleResize = currentSystemTime()
needsCanvasRedraw = false

while(running) {
    if (currentSystemTime() - timeOfLastBackgroundChange > 500) {
        changeBGColor()
        timeOfLastBackgroundChange = currentSystemTime()
        needsCanvasRedraw = true
    }

    if (currentSystemTime() - timeOfLastCircleResize > n) {
        resizeCircle()
        timeOfLastCircleResize = currentSystemTime();
        needsCanvasRedraw = true
    }

    if (needsCanvasRedraw) {
        drawUpdatedObjects()
        needsCanvasRedraw = false
    }

Basically, within your loop, you keep track of the last time you changed the background color and resized your circles. In every iteration of the loop, you check if enough time has elapsed to warrant another background change or circle resize. If it has, then you make the change and record the current time of the change so you can record the elapsed time for the next change. The needsCanvasRedraw flag lets you redraw only when something has changed rather than every loop iteration.

于 2013-10-07T03:23:52.757 回答