public class MySurfaceView extends SurfaceView implements Runnable,SurfaceHolder.Callback{
public Thread thread;
public Canvas canvas;
public Bitmap bitmap = Bitmap.createBitmap(80, 60, Bitmap.Config.ARGB_8888);
public SurfaceHolder surfaceHolder;
public Paint paint;
public Context context;
int map_width,map_height;
public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
this.surfaceHolder = this.getHolder();
this.surfaceHolder.addCallback(this);
this.paint = new Paint();
this.paint.setColor(Color.YELLOW);
this.paint.setTextSize(20);
this.context = context;
scale = context.getResources().getDisplayMetrics().density;
map_width = attrs.getAttributeIntValue(null, "map_width",164);
map_height = attrs.getAttributeIntValue(null, "map_height",160);
Log.d("ssss", "w = " + map_width + " h = " + map_height);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("ssss", "tw = " + this.getWidth() + " th = " + this.getHeight());
map_height = this.getHeight();
map_width = this.getWidth();
setBitmap(this.bitmap);
return super.onTouchEvent(event);
}
public void updataSize(){
Log.d("ssss", "tw1 = " + this.getWidth() + " th = " + this.getHeight());
map_height = this.getHeight();
map_width = this.getWidth();
if(map_height != 0 && map_height != 0)
setBitmap(this.bitmap);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
public void setBitmap(Bitmap bitmap){
this.bitmap = Bitmap.createScaledBitmap(bitmap, map_width, map_height, true);
//this.bitmap = bitmap;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.d("ssss", "surfaceChanged");
this.thread = new Thread(this);
this.thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
this.surfaceHolder.removeCallback(this);
Log.d("ssss", "surfaceDestroyed");
}
@Override
public void run() {
while(true){
synchronized (this){
canvas = surfaceHolder.lockCanvas();
if (bitmap != null&& canvas != null) {
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bitmap, 0, 0, paint);
}
}
if(canvas != null){
surfaceHolder.unlockCanvasAndPost(canvas);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void setWH(float w, float h){
this.map_width = dip2px(w);
this.map_height = dip2px(h);
}
float scale;
public int dip2px(float dpValue) {
return (int) (dpValue * scale + 0.5f);
}
public float dip2px(short dpValue) {
return (dpValue * scale + 0.5f) * 5f;
}
}