您好,登录后才能下订单哦!
//MysurfaceView.java
package com.example.surfaceview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
public class MysurfaceView extends SurfaceView implements Callback{
private SurfaceHolder sfh;
private Paint paint;
private int textX=10,textY=10;
public MysurfaceView(Context context)
{
super(context);
sfh=this.getHolder();//控制SurfaceView的大小 格式 主要用于监听SurfaceView的状态
//其实surfaceView只是保存当前视图的像素数据 在使用surfaceView时 并不会与surfaceview直接打交道
//而是通过surfaceHolder来控制 使用surfaceHolder的lockCanvas()函数获取到surfaceView的
//canvas对象 。在通过在canvas上绘制内容来修改surfaceView中的数据
//locakCanvas不仅获取canvas 还对获取的canvas进行加锁
sfh.addCallback(this);//将其监听接口实例传入..完成对surfaceView的监听
paint=new Paint();
paint.setColor(Color.WHITE);
setFocusable(true);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
myDraw();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void myDraw()
{
Canvas canvas=sfh.lockCanvas();
canvas.drawRect(0, 0,this.getWidth(),this.getHeight(),paint);//the first method 绘制一个和手机屏幕一样大小的矩形
canvas.drawColor(Color.BLACK);//the second methos绘制颜色填充整个屏幕
canvas.drawRGB(0,0,0);//the third method 绘制颜色填充整个屏幕
canvas.drawText("game", textX, textY, paint);
sfh.unlockCanvasAndPost(canvas);
}
public boolean onTouchEvent(MotionEvent event)
{
textX=(int)event.getX();
textY=(int)event.getY();
myDraw();
invalidate();
return true;
}
}
//MainActivity.java如下:
package com.example.surfaceview;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MysurfaceView(this));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。