如下图:
代码如下
public class MyView extends View {
public MyView(Context context) {
super(context);
setBackgroundColor(0x5500ff00);
init();
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
private Paint paint;
private int left,top;
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
left = 50;
top = 100;
paint.setTextSize(30);
}
/**
* 在画布上画矩形
* @param canvas
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.RED);
Rect block = new Rect(left, top, left+100, top+100);
canvas.drawRect(block, paint);
String text = "Hello";
Rect textRect = new Rect();
paint.getTextBounds(text,0,text.length(),textRect);
int x = block.centerX() - textRect.centerX();
int y =block.centerY() - textRect.centerY();
paint.setColor(Color.WHITE);
canvas.drawText(text,x,y,paint);
}
private Point lastPoint;
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action){
case MotionEvent.ACTION_DOWN:
if(null == lastPoint){
lastPoint = new Point();
}
int x = (int) event.getX();
int y = (int) event.getY();
lastPoint.set(x,y);
break;
case MotionEvent.ACTION_MOVE:
int x1 = (int) event.getX();
int y1 = (int) event.getY();
int xDis = x1- lastPoint.x;
int yDis = y1 - lastPoint.y;
left += xDis;
top += yDis;
invalidate();
lastPoint.set(x1,y1);
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}