满意答案
hnyywch
推荐于 2016.04.07
采纳率:44% 等级:13
已帮助:7411人
继承SurfaceView 类写的也可以继承View类写
public class GetWHSurfaceView extends SurfaceView implements Callback,Runnable{
private int textX = 20, textY = 20;
private int screenHeight;
private int screenWidth;
private SurfaceHolder sfh;
private boolean flag;
private Thread th;
//画布
private Canvas canvas;
public GetWHSurfaceView(Context context) {
super(context);
sfh = this.getHolder();
sfh.addCallback(this);
canvas = new Canvas();
Paint paintText;
paintText = new Paint();
this.setKeepScreenOn(true);
setFocusable(true);
setFocusableInTouchMode(true);
}
/**
* 重写触屏事件函数
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
//玩家手指点击屏幕的动作
if (event.getAction() == MotionEvent.ACTION_DOWN) {
textX = x;
textY = y;
//玩家手指抬起离开屏幕的动作
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
textX = x;
textY = y;
//玩家手指在屏幕上移动的动作
} else if (event.getAction() == MotionEvent.ACTION_UP) {
textX = x;
textY = y;
}
return true;
}
public void myDraw()
{
//绘制背景色
canvas = sfh.lockCanvas();
try {
if(canvas != null)
{
//创建一个画笔的实例
Paint paint = new Paint();
paint.setColor(Color.BLACK);
canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), paint);
//设置画笔的颜色
paint.setColor(Color.WHITE);
//绘制文本
canvas.drawText(String.valueOf(textX), textX, textY, paint);
canvas.drawText(String.valueOf(textY), textX+25, textY, paint);
canvas.drawText(String.valueOf(screenWidth), 280, 20, paint);
canvas.drawText(String.valueOf(screenHeight),280+20, 20, paint);
}
} catch (Exception e) {
}finally
{
sfh.unlockCanvasAndPost(canvas);
}
}
@Override
public void run() {
while(flag)
{
long start = System.currentTimeMillis();
myDraw();
long end = System.currentTimeMillis();
try {
if(end - start < 50)
{
Thread.sleep(50 -(end-start));
System.out.print("run");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
screenHeight = this.getHeight();
screenWidth = this.getWidth();
flag = true;
th = new Thread(this);
th.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
flag = false;
}
}
00分享举报