Android画布drawRect()也重绘以前的画图
问题描述:
我花了整整一天的时间试图弄清楚,如何绘制随机颜色的方块,填满整个屏幕。我认为会发生这样的情况,当drawRect()被调用时,它会重绘以前的绘制,这没有任何意义,但是我得到了它。这是代码,我不知道还有什么可以解决这个问题,这是结果。 http://i.imgur.com/a083U0a.pngAndroid画布drawRect()也重绘以前的画图
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);
}
}
答
你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);
}
}
}
你可以尝试使用无效的();在你的onDraw()的结尾处;功能? –
是的,我试过了,但它开始闪烁着不同的颜色,但仍然没有正确显示广场 –
是的,不要这样做。它只是将你的'View'放在一个无限循环中。首先,查看'drawRect()'方法的参数。第三和第四个参数是“右”和“底”,而不是“宽度”和“高度”。其次,检查内部的'for'循环。你在终止条件中使用外循环的计数器;即'i