理解 Canvas.onDraw() 的概念有问题吗?

发布于 2024-12-02 21:58:43 字数 1134 浏览 6 评论 0原文

我编写了以下简单的代码来查看渲染的行为。在此代码中,我正在更改屏幕的颜色。

我不明白的是,为什么这段代码会永远运行?我没有使用无限循环,但这段代码将永远运行!

请告诉我原因。谢谢

package kamalan.com.androidbasicstarter;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class RenderViewTest extends Activity{

    class RenderView extends View{
        Random rand = new Random();

        public RenderView(Context context) {
            super(context);
        }

        protected void onDraw(Canvas canvas){
            canvas.drawRGB(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
            invalidate();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(new RenderView(this));
    }
}

I have written following simple code to see the behavior of rendering. In this code i'm changing the color of screen.

The thing that I can't understand is, why this code is running for ever? I didn't use unlimited loop but this code will run for ever!

Please tell me the reason. Thanks

package kamalan.com.androidbasicstarter;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class RenderViewTest extends Activity{

    class RenderView extends View{
        Random rand = new Random();

        public RenderView(Context context) {
            super(context);
        }

        protected void onDraw(Canvas canvas){
            canvas.drawRGB(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
            invalidate();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(new RenderView(this));
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饮湿 2024-12-09 21:58:43

invalidate 导致重绘。从 onDraw 调用它通常(总是?)是个坏主意,因为它会导致立即再次调用 onDraw。这就是你所看到的。

invalidate causes a redraw. It's usually (always?) a bad idea to call that from onDraw, because it will cause onDraw to be called again immediately. Which is what you are seeing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文