我花了一整天的时间试图找出,如何用随机颜色绘制正方形,填满整个屏幕。我认为发生的是,当调用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);
}
}
答案 0 :(得分:0)
您的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);
}
}
}