|
我用SurfaceView绘图时,想让一个星星在屏幕内随机闪动,可是每动一次,星星就多一个,郁闷了
该怎么破解啊;
以下是我的代码:
package com.icss;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
public class CustomSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
//获surface管理器
private SurfaceHolder sholder;
private int screen_width;
private int screen_height;
//声明画布
private Canvas canvas;
//n声明一个线程
private MyThread mythread;
//获得画笔
private Paint paint;
//获得图片
private Bitmap star_green;
private Bitmap star_red;
private Bitmap star_white;
public CustomSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
System.out.println("CustomSurfaceView................");
//实例化surface
this.sholder = this.getHolder();
sholder.addCallback(this);
//实例化线程
mythread = new MyThread();
//实例化画笔
paint = new Paint();
paint.setStyle(Style.STROKE);
//初始化屏幕宽、高
WindowManager manager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
this.screen_height = display.getHeight();
this.screen_width = display.getWidth();
//初始化图片
star_green = BitmapFactory.decodeResource(this.getResources(), R.drawable.toolbar_backup_green);
star_red = BitmapFactory.decodeResource(this.getResources(), R.drawable.toolbar_backup_red);
star_white = BitmapFactory.decodeResource(this.getResources(), R.drawable.toolbar_backup_white);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("surfaceCreated................");
mythread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
System.out.println("surfaceChanged................");
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
System.out.println("surfaceDestroyed................");
try {
mythread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyThread extends Thread{
@Override
public void run() {
while(true){
float left = (float)Math.random()*screen_width;
float top = (float)Math.random()*screen_height;
canvas = sholder.lockCanvas();
canvas.drawBitmap(star_green, left, top, paint);
sholder.unlockCanvasAndPost(canvas);
try {
sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} |
|