程序效果是:在屏幕上画一个圆,可以用鼠标任意移动到屏幕上任何一个地方:
package com.ray.view;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class TestView extends Activity {
float x = 0;
float y = 0;
View myView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//值得一提的是,由于画圆参照的坐标系(以系统信息栏的左下侧为原点)
//和MotionEvent获取的x,y坐标参照(以屏幕坐上角为原点)的坐标系不同,
//如果不设置全屏的话,会出现鼠标中心跟圆心不一致的情况。
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,WindowManager.LayoutParams. FLAG_FULLSCREEN);
myView = new MyView(this);
setContentView(myView);
}
public boolean onTouchEvent(MotionEvent event) {
x = event.getX();
y = event.getY();
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
myView.invalidate();
break;
case MotionEvent.ACTION_UP:
myView.invalidate();
break;
case MotionEvent.ACTION_MOVE:
myView.invalidate();
break;
}
return super.onTouchEvent(event);
}
class MyView extends View{
protected void onDraw(Canvas canvas) {
Paint mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setAntiAlias(true);
canvas.drawCircle(x, y, 20, mPaint);
super.onDraw(canvas);
}
public MyView(Context context) {
super(context);
}
}
}
package com.ray.view;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class TestView extends Activity {
float x = 0;
float y = 0;
View myView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//值得一提的是,由于画圆参照的坐标系(以系统信息栏的左下侧为原点)
//和MotionEvent获取的x,y坐标参照(以屏幕坐上角为原点)的坐标系不同,
//如果不设置全屏的话,会出现鼠标中心跟圆心不一致的情况。
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,WindowManager.LayoutParams. FLAG_FULLSCREEN);
myView = new MyView(this);
setContentView(myView);
}
public boolean onTouchEvent(MotionEvent event) {
x = event.getX();
y = event.getY();
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
myView.invalidate();
break;
case MotionEvent.ACTION_UP:
myView.invalidate();
break;
case MotionEvent.ACTION_MOVE:
myView.invalidate();
break;
}
return super.onTouchEvent(event);
}
class MyView extends View{
protected void onDraw(Canvas canvas) {
Paint mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setAntiAlias(true);
canvas.drawCircle(x, y, 20, mPaint);
super.onDraw(canvas);
}
public MyView(Context context) {
super(context);
}
}
}