【发布时间】: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()方法的参数。第三个和第四个参数是right和bottom,而不是width和height。其次,检查内部for循环。您在终止条件中使用外部循环的计数器;即i <= numberPerRow.
标签: java android canvas drawrect