1. 程式人生 > >小球跟隨滑鼠晃動

小球跟隨滑鼠晃動

CustomView

public class CustomView extends View {
    Paint paint;
    float mTouchX,mTouchY;
    public CustomView(Context context) {
        super(context);
        init();
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint=new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(10);
        paint.setTextSize(60);
        paint.setStyle(Paint.Style.FILL);
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    //獲取點選位置的X Y
                    mTouchX=event.getX();
                    mTouchY=event.getY();
                }else if(event.getAction()==MotionEvent.ACTION_MOVE){
                    //獲取點選位置的 X Y
                    mTouchX=event.getX();
                    mTouchY=event.getY();
                }
                invalidate();
                return true;
            }
        });
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(mTouchX,mTouchY,50,paint);
    }
}

MainActivity裡不需要寫