我创建了一个视图类型类,在其中我正在绘制一些框的 onDraw() 方法。我没有成功的是,我想在 3-5 秒后消失这些框。为此,我正在使用计时器和 timerTask。在 TimerTask 中,我重写了将 Paint 对象的颜色更改为白色的方法 run()。背景颜色也是白色的,所以它会产生删除框的效果。你们能帮帮我吗??
public class PlayView extends View
{
private float width,height;
private int touchatX, touchatY;
private boolean isanyBox, clearCanvas;
private Point points[];
private Paint box;
Timer timer;
TimerTask task;
// Set the number of points to be generated so we print that number of boxes on the board
public void nPoints(int n)
{
points = new Point[n];
box = new Paint();
box.setColor(Color.BLUE);
}
public void init()
{
isanyBox = false;
clearCanvas = true;
timer = new Timer();
task = new TimerTask()
{
@Override
public void run()
{
box.setColor(Color.WHITE);
}
};
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
// TODO Auto-generated method stub
width = w/6f;
height = h/6f;
Log.d("playview", getWidth()+" "+getHeight());
super.onSizeChanged(w, h, oldw, oldh);
}
public PlayView(Context context)
{
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
init();
}
// Randomly generate the points and draw boxes on these points
public void generatePoints(int np)
{
Time sec = new Time();
Random random_Xpoints = new Random();
Random random_Ypoints = new Random();
random_Xpoints.setSeed(sec.second);
random_Ypoints.setSeed(sec.second);
nPoints(np); // set the number of points to be generated
for(int i=0; i<np; i++)
{
points[i] = new Point();
points[i].setX( ((random_Xpoints.nextInt(getWidth())/(int)width)*(int)width));
points[i].setY( ((random_Ypoints.nextInt(getHeight())/(int)height)*(int)height));
Log.d("Point "+1, points[i].getX()+" "+points[i].getY());
}
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
// TODO Auto-generated method stub
invalidate();
isanyBox = true;
touchatX = (int) ((int) (event.getX()/width)*width);
touchatY = (int) ((int) (event.getY()/height)*height);
Log.d("onTouchEvent", event.getX()+" "+event.getY()+" "+touchatX+" "+touchatY);
invalidate();
return super.onTouchEvent(event);
}
public void onDraw(Canvas canvas)
{
Paint lineColor = new Paint();
lineColor.setColor(Color.BLACK);
//Box property
Paint boxColor = new Paint();
boxColor.setColor(Color.BLUE);
//Draw horizontal lines
for(int i=0; i<6; i++)
{
canvas.drawLine(0, i*height, getWidth(), i*height, lineColor);
}
//Draw vertical lines
for(int j=0; j<6; j++)
{
canvas.drawLine(j*width, 0, j*width, getHeight(), lineColor);
}
if(isanyBox)
{
canvas.drawRect(touchatX+2, touchatY+2, touchatX+width-1, touchatY+height-2, boxColor);
}
generatePoints(5);
for(int j=0; j<5; j++)
{
canvas.drawRect(points[j].getX()+2, points[j].getY()+2, points[j].getX()+width-1, points[j].getY()+height-2, box);
Log.d("BoxColor", ""+box);
}
if(clearCanvas)
{
timer.schedule(task, 3000);
clearCanvas = false;
invalidate();
}
}
}