重写View中的onDraw函数可以实现画图.代码如下:
@Override
public void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.WHITE);
canvas.drawText("Hello world", pX, pY, paint);
}
要更新画的形状需要调用invalidate()函数.下面是点哪里在哪里画一行文字的代码.
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 MoveTextView extends View {
private int pX;
private int pY;
public MoveTextView(Context context) {
super(context);
}
@Override
public void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.WHITE);
canvas.drawText("Hello world", pX, pY, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
pX = x;
pY = y;
}
invalidate();
return true;
}
}