【问题标题】:Android canvas drawRect() also redraws previous drawsAndroid canvas drawRect() 还会重绘以前的绘图
【发布时间】:2023-04-08 13:40:01
【问题描述】:

我花了一整天的时间试图弄清楚如何用随机颜色绘制正方形,填满整个屏幕。我认为发生的事情是,当调用 drawRect() 时,它会重绘以前的绘图,这没有任何意义,但它就是我所得到的。这是代码,我不知道还能做什么来解决这个问题,这是结果。 http://i.imgur.com/a083U0a.png

public class MyView extends View {
    public MyView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);
        int numberPerRow = 10;
        int x = getWidth()/numberPerRow;
        int y = getHeight();



        for(int i = 0; i < 50; i++){
            for (int j = 0; i <= numberPerRow; j++){
                Paint paintTopRight = new Paint();
                int randColor = randomColor();
                paintTopRight.setColor(randColor);
                canvas.drawRect(j*x,i*x,x,x,paintTopRight);
            }
        }
    }


    public int randomColor() {

        int r = (int) (0xff * Math.random());
        int g = (int) (0xff * Math.random());
        int b = (int) (0xff * Math.random());

        return Color.rgb(r, g, b);
    }
}

【问题讨论】:

  • 你可以尝试使用invalidate();在 onDraw() 结束时;功能?
  • 是的,我试过了,但它开始以不同的颜色闪烁,但仍无法正确显示正方形
  • 是的,不要那样做。它只是将您的View 置于无限循环中。首先,查看drawRect() 方法的参数。第三个和第四个参数是rightbottom,而不是widthheight。其次,检查内部for 循环。您在终止条件中使用外部循环的计数器;即i &lt;= numberPerRow.

标签: java android canvas drawrect


【解决方案1】:

您的for 循环似乎有错字;当你应该使用`j时,你使用i

将新的onDraw(Canvas canvas) 方法更改为

@Override
protected void onDraw(Canvas canvas) {

    super.onDraw(canvas);
    int numberPerRow = 10;
    int x = getWidth()/numberPerRow;
    int y = getHeight();



    for(int i = 0; i < 50; i++){
        for (int j = 0; j <= numberPerRow; j++){
            Paint paintTopRight = new Paint();
            int randColor = randomColor();
            paintTopRight.setColor(randColor);
            canvas.drawRect(j*x,i*x,x,x,paintTopRight);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多