自定義View 手指拖動圖片移動
阿新 • • 發佈:2018-12-19
public class TurnTableView extends View { private int mHeight; private int mWidth; private int x; private int y; private boolean mOnBall; private int mRadius = 90; public TurnTableView(Context context) { this(context,null); } public TurnTableView(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public TurnTableView(Context context, @Nullable 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(); //獲取螢幕的正中心點 x = mWidth / 2; y = mHeight / 2; } @Override//繪製 protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint();//畫筆 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);//設定圖片 canvas.drawBitmap(bitmap,x,y,paint);//放入圖片 } //手勢監聽器,可以得到使用者手指在螢幕上滑動的座標 @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: float newX = event.getX(); float newY = event.getY(); //進行判斷,判斷使用者的手指是否按在了圖上 mOnBall = isOnBall(newX,newY); Toast.makeText(getContext(), "使用者的手指是否點到圖上了嗎?"+mOnBall, Toast.LENGTH_SHORT).show(); break; case MotionEvent.ACTION_MOVE: //只用使用者點到圖上時,我才讓它動 if (mOnBall){ x = (int) event.getX(); y = (int) event.getY(); //回撥OnDrawer方法 postInvalidate(); } break; case MotionEvent.ACTION_UP: break; } return true; } //,判斷使用者的手指是否按在了圖上 private boolean isOnBall(float newX, float newY) { //勾股定理的絕對值 double sqrt = Math.sqrt((newX - x) * (newX - x) + (newY - y) * (newY - y)); //判斷絕對值是否小於等於半徑 if(sqrt <= mRadius){ return true; } return false; } }