我试图在屏幕上随机画两个矩形使用ondraw方法,我想清除屏幕,使两个新的矩形每2秒。所以我把invalidate() Package 在一个计时器中。但是,当我运行此代码时,它首先显示两个矩形,并在2秒后停止运行。我猜我的计时器有问题,因为我的代码在添加计时器之前运行良好。为什么这不起作用,我应该如何修复它,使它每2秒绘制2个矩形(删除以前的矩形)?提前谢谢。
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
int width = canvas.getWidth();
int height = canvas.getHeight();
int rectangleWidth = width / 5;//Width of a rectangle
int rectangleHeight = height / 15; //height of a rectangle
for(int i = 0; i< 2; i++) {
randomLeft = randomGenerator1.nextInt(width - rectangleWidth);
colors = new String[]{"red", "black", "blue", "green", "yellow"};
int randomColorIndex = randomGenerator2.nextInt(colors.length);
randomColor = new Paint();
randomColor.setColor(Color.parseColor(colors[randomColorIndex]));
randomColor.setStyle(Paint.Style.FILL);
Rectangle newRectangle = new Rectangle(rectangleWidth, rectangleHeight);
newRectangle.setColor(randomColor);
rectangles.add(newRectangle);
redRect.set(randomLeft, y, randomLeft + rectangleWidth, y + rectangleHeight);
rects.add(redRect);
canvas.drawRect(redRect, randomColor);
}
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
invalidate();
}
}, 2000);
}
暂无答案!
目前还没有任何答案,快来回答吧!