在屏幕上绘制一个小球,可以跟随手指移动
练习心得
- View的回调方法onDraw(Canvas)负责在画布上绘制view,而该方法由View的invalidate()触发回调,即除首次绘制外每次绘制都需要view.invalidate触发
- Context的getWindow()可获得当前的窗口对象,通过该对象可设置窗口样式、背景等属性,所有的窗口设置都要在setContentView之前
- 获取窗口属性通过WindowManager,流程是getWindowManager->getDefaltDisplay->new DisplayMetrics->display.getMetrics(displayMetrics)->displayMetrics.get***获取
- 手机是以左上角定义为坐标(0,0)的,然后向右、向下逐渐增大
代码样例
自定义View
/**
* Created by Rambo
*/
public class FollowBall extends View implements Contants{
private float startX;// 圆球中心起始X坐标
private float startY;// 圆球中心起始Y坐标
private int radius;// 圆球半径
public FollowBall(Context context, AttributeSet attrs, float startX, float startY, int radius) {
super(context, attrs);
this.startX = startX;
this.startY = startY;
this.radius = radius;
}
/**
* 绘制视图
* @param canvas 绘制视图的画布
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(startX, startY, radius, paint);
}
/**
* View的touch动作回调处理
* @param event
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
startX = event.getX();
startY = event.getY();
Log.v(TAG, "touchX=" + startX + ",touchY=" + startY);
this.invalidate();// 触发回调对应View的onDraw方法
return true;// 时间消费掉不再向其归属activity传递
}
}
Activity
public class FollowBallActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* 对窗口的设置要在setContentView前完成
*/
{
requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉窗口标题
/*
设置window属性,window即windowManager中维护的最顶层View
*/
Window window = getWindow();
// 设置为全屏
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// 设置window背景
window.setBackgroundDrawableResource(R.drawable.background);
}
// 获取窗口管理器,并获取应用展示区域(即DisplayMetrics),进而获取展示区域的长、宽、密度等信息
// 流程就是getWindowManager->getDdfaultDisplay->new DisplayMetrics->getMetrics
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
//注:手机是以左上角定义为坐标(0,0)的,然后向右、向下逐渐增大
int radius = 20; //球的半径
int startX = displayMetrics.widthPixels/2; //初始横向位置在屏幕中间
int startY = radius; // 初始纵向位置紧贴上方
FollowBall followBall = new FollowBall(this, null, startX, startY, radius);
// 展示跟踪球
setContentView(followBall);
}
}
最终效果如图: