自定义View(小球随手指移动)

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {

Paint paint=new Paint();
private int width;
private int heigh;
private float currX=0;
private float currY=0;

public MyView(Context context) {
super(context);

}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);

}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);

}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width=MeasureSpec.getSize(widthMeasureSpec);
heigh=MeasureSpec.getSize(heightMeasureSpec);
currX=width/2;
currY=heigh/2;
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.RED);
paint.setAntiAlias(true);
canvas.drawCircle(currX,currY,60, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
currX=event.getX();
currY=event.getY();
postInvalidate();
break;
case MotionEvent.ACTION_MOVE:
currX=event.getX();
currY=event.getY();
postInvalidate();
break;
case MotionEvent.ACTION_UP:

break;
case MotionEvent.ACTION_CANCEL:

break;

}

return true;

}
}

posted @ 2016-05-09 15:11  夏夜微凉  阅读(285)  评论(0编辑  收藏  举报