方法一:
新建"MyView"类
package onTouchEvent; import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View; public class MyView extends View {
private int textX=,textY=;
public MyView(Context context) {
super(context);
setFocusable(true);
// TODO Auto-generated constructor stub
}
//画笔onDraw方法
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//初始化画笔
Paint paint=new Paint();
//设置颜色
paint.setColor(Color.GREEN);
//设置字体大小
paint.setTextSize();
//在画布上写文字
canvas.drawText("Android", textX, textY, paint);
} @Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
//获取用户手指触屏的X坐标赋值与文本的X坐标
textX=(int)event.getX();
//获取用户手指触屏的Y坐标赋值与文本的Y坐标
textY=(int)event.getY();
//重绘画布
invalidate();
return true; } }
MainActivity中将setContentView设置为当前MyView,即
setContentView(new MyView(this));
执行效果图如下:
方法二:
方法二的不用之处就是使用了SurfaceHolder(选择器)方法
package com.example.cdp; 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 {
//定义一个SurfaceHolder相当于选择器
private SurfaceHolder sfh;
private int textX=,textY=;
public MySurfaceView(Context context) {
super(context);
// TODO Auto-generated constructor stub
//获得SurfaceHolder对象
sfh = getHolder();
//监听surface的生命周期
sfh.addCallback(this);
//获得焦点
setFocusableInTouchMode(true);
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub }
@Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
myDraw();
} private void myDraw() {
// TODO Auto-generated method stub
new Thread(){
public void run() {
// 通过SurfaceHolder对象获得 Surface的Canvas成员变量,并且锁住Canvas
Canvas canvas = sfh.lockCanvas();
// 刷屏
canvas.drawColor(Color.BLACK);
// 初始画笔
Paint paint = new Paint();
// 设置抗锯齿,文字清晰点,不过相对比较耗性能
paint.setAntiAlias(true);
// 设置画笔颜色
paint.setColor(Color.RED);
// 设置文字大小
paint.setTextSize();
// 画(写)文字
canvas.drawText("Android", textX, textY, paint);
// 画完后,再将缓存的内容渲染到屏幕上,同时也是解锁
sfh.unlockCanvasAndPost(canvas);
};
}.start();
} @Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
//return super.onTouchEvent(event);
// 获取用户手指触屏的X坐标赋值与文本的X坐标
textX = (int) event.getX();
// 获取用户手指触屏的Y坐标赋值与文本的Y坐标
textY = (int) event.getY();
myDraw();
return true;
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub } }
执行效果图: