标签:surfaceview 画布 刷新方法
//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;
}
}
本文出自 “hagar” 博客,请务必保留此出处http://7832308.blog.51cto.com/7822308/1430460
android基础之SurfaceView视图中对画布的3种刷新方法,布布扣,bubuko.com
android基础之SurfaceView视图中对画布的3种刷新方法
标签:surfaceview 画布 刷新方法
原文地址:http://7832308.blog.51cto.com/7822308/1430460