1. 程式人生 > >實現拖動小球

實現拖動小球

action_main

// 先建立類

 <wanghuiqi.bawie.com.drag_balls.DrawerView
            android:id="@+id/ball"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

DrawerView

package wanghuiqi.bawie.com.drag_balls;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class DrawerView extends View {

    private int mWidth;
    private int mHeight;
    private int mMoveX;
    private int mMoveY;
    private Boolean mOnBall;
    private int mRadius=20;

    public DrawerView(Context context) {
        this(context, null);
    }

    public DrawerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DrawerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    //測量方法
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //得到小球的寬高,預設全屏
        mWidth = this.getWidth();
        mHeight = this.getHeight();
        //設定小球的位置
        mMoveX = mWidth / 2;
        mMoveY = mHeight / 2;
    }

    //繪製
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //建立畫筆
        Paint paint = new Paint();
        //設定畫筆顏色
        paint.setColor(Color.RED);
        //畫出小球,引數(X,Y座標,半徑)
        canvas.drawCircle(mMoveX, mMoveY, mRadius, paint);
    }

    //觸控事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //得到當前的座標
                float downX = event.getX();
                float downY = event.getY();
                //判斷滑鼠是不是在球上,點選任意位置,小球就會過去
                mOnBall = isOnBall(downX, downY);
                Toast.makeText(getContext(), "使用者的手指是否點到園內" + mOnBall,
                        Toast.LENGTH_SHORT).show();
                break;
            case MotionEvent.ACTION_MOVE:
                //使用者點到園內時,圓才能動
                if (mOnBall) {
                    mMoveX = (int) event.getX();
                    mMoveY = (int) event.getY();
                }
                //重新呼叫onDraw
                postInvalidate();
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return true;
    }

    //判斷使用者的手指是否在園內
    private Boolean isOnBall(float downX, float downY) {
        //勾股定理的絕對值
        double sqrt = Math.sqrt((downX - mMoveX) * (downX - mMoveX)
                + ((downY - mMoveY) * (downY - mMoveY)));
        //判斷絕對值是否小於等於半徑
        if (sqrt <= mRadius) {
            return true;
        }
        return false;
    }
}