android圓形旋轉選單,並支援移動換位功能
阿新 • • 發佈:2019-01-27
LZ最近接手公司一個專案,需要寫一個圓形的旋轉選單,並且支援選單之間的移動換位,本來以為這種demo應該網上是很多的,想不到度娘也是幫不了我,空有旋轉功能但是卻不能換位置,所以LZ就只能靠自己摸索了。
最終LZ參考了網上的部分程式碼,重寫了一個自定義的view終於實現了這個看似很吊,卻沒有實際意義的功能。在此貢獻出來給廣大碼農們共享。
話不多說,先上程式碼:
自定義view類:
layout檔案程式碼:public class RoundSpinView extends View { private Paint mPaint = new Paint(); private PaintFlagsDrawFilter pfd; private int startMenu; //選單的第一張圖片的資源id // stone列表 private BigStone[] mStones; // 數目 private static final int STONE_COUNT = 3; // 圓心座標 private int mPointX = 0, mPointY = 0; // 半徑 private int mRadius = 0; // 每兩個點間隔的角度 private int mDegreeDelta; private int menuRadius; // 選單的半徑 private int mCur = -1; // 正在被移動的menu; private boolean[] quadrantTouched; //對每個象限觸控情況的記錄 // Touch detection private GestureDetector mGestureDetector; private onRoundSpinViewListener mListener; //自定義事件監聽器 private final static int TO_ROTATE_BUTTON = 0; //旋轉按鈕; private Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case TO_ROTATE_BUTTON: float velocity = Float.parseFloat(msg.obj.toString()); rotateButtons(velocity/75); velocity /= 1.0666F; new Thread(new FlingRunnable(velocity)).start(); break; default: break; } }; }; public interface onRoundSpinViewListener{ public void onSingleTapUp(int position); //監聽每個選單的單擊事件 } public RoundSpinView(Context context,AttributeSet attrs) { super(context,attrs); if(attrs!=null){ TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RoundSpinView); startMenu = a.getResourceId(R.styleable.RoundSpinView_menuStart, 0); } pfd = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG); mPaint.setColor(Color.WHITE); mPaint.setStrokeWidth(2); mPaint.setAntiAlias(true); //消除鋸齒 mPaint.setStyle(Paint.Style.STROKE); //繪製空心圓 PathEffect effects = new DashPathEffect(new float[]{5,5,5,5},1); mPaint.setPathEffect(effects); quadrantTouched = new boolean[] { false, false, false, false, false }; mGestureDetector = new GestureDetector(getContext(), new MyGestureListener()); setupStones(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); mPointX = this.getMeasuredWidth()/2; mPointY = this.getMeasuredHeight()/2; //初始化半徑和選單半徑 mRadius = mPointX-mPointX/5; menuRadius = (int)(mPointX/5.5); computeCoordinates(); } /** * 初始化每個點 */ private void setupStones() { mStones = new BigStone[STONE_COUNT]; BigStone stone; int angle = 270; mDegreeDelta = 360 / STONE_COUNT; for (int index = 0; index < STONE_COUNT; index++) { stone = new BigStone(); if (angle >= 360) { angle -= 360; }else if(angle < 0){ angle += 360; } stone.angle = angle; stone.bitmap = BitmapFactory.decodeResource(getResources(), startMenu + index); angle += mDegreeDelta; mStones[index] = stone; } } /** * 重新計算每個點的角度 */ private void resetStonesAngle(float x, float y) { int angle = computeCurrentAngle(x, y); Log.d("RoundSpinView", "angle:" + angle); for (int index = 0; index < STONE_COUNT; index++) { mStones[index].angle = angle; angle += mDegreeDelta; } } /** * 計算每個點的座標 */ private void computeCoordinates() { BigStone stone; for (int index = 0; index < STONE_COUNT; index++) { stone = mStones[index]; stone.x = mPointX + (float) (mRadius * Math.cos(Math.toRadians(stone.angle))); stone.y = mPointY + (float) (mRadius * Math.sin(Math.toRadians(stone.angle))); } } /** * 計算某點的角度 * * @param x * @param y * @return */ private int computeCurrentAngle(float x, float y) { float distance = (float) Math .sqrt(((x - mPointX) * (x - mPointX) + (y - mPointY) * (y - mPointY))); int degree = (int) (Math.acos((x - mPointX) / distance) * 180 / Math.PI); if (y < mPointY) { degree = -degree; } Log.d("RoundSpinView", "x:" + x + ",y:" + y + ",degree:" + degree); return degree; } private double startAngle; @Override public boolean dispatchTouchEvent(MotionEvent event) { // resetStonesAngle(event.getX(), event.getY()); // computeCoordinates(); // invalidate(); int x, y; if (event.getAction() == MotionEvent.ACTION_DOWN) { x = (int) event.getX(); y = (int) event.getY(); mCur = getInCircle(x, y); if (mCur == -1) { startAngle = computeCurrentAngle(x, y); } } else if (event.getAction() == MotionEvent.ACTION_MOVE) { x = (int) event.getX(); y = (int) event.getY(); if (mCur != -1) { mStones[mCur].x = x; mStones[mCur].y = y; invalidate(); } else { double currentAngle = computeCurrentAngle(x, y); rotateButtons(startAngle - currentAngle); startAngle = currentAngle; } } else if (event.getAction() == MotionEvent.ACTION_UP) { x = (int) event.getX(); y = (int) event.getY(); if (mCur != -1) { computeCoordinates(); int cur = getInCircle(x, y); if (cur != mCur && cur != -1) { int angle = mStones[mCur].angle; mStones[mCur].angle = mStones[cur].angle; mStones[cur].angle = angle; } computeCoordinates(); invalidate(); mCur = -1; } } // set the touched quadrant to true quadrantTouched[getQuadrant(event.getX() - mPointX, mPointY - event.getY())] = true; mGestureDetector.onTouchEvent(event); return true; } private class MyGestureListener extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // get the quadrant of the start and the end of the fling int q1 = getQuadrant(e1.getX() - mPointX, mPointY - e1.getY()); int q2 = getQuadrant(e2.getX() - mPointX, mPointY - e2.getY()); // the inversed rotations if ((q1 == 2 && q2 == 2 && Math.abs(velocityX) < Math .abs(velocityY)) || (q1 == 3 && q2 == 3) || (q1 == 1 && q2 == 3) || (q1 == 4 && q2 == 4 && Math.abs(velocityX) > Math .abs(velocityY)) || ((q1 == 2 && q2 == 3) || (q1 == 3 && q2 == 2)) || ((q1 == 3 && q2 == 4) || (q1 == 4 && q2 == 3)) || (q1 == 2 && q2 == 4 && quadrantTouched[3]) || (q1 == 4 && q2 == 2 && quadrantTouched[3])) { // CircleLayout.this.post(new FlingRunnable(-1 // * (velocityX + velocityY))); new Thread(new FlingRunnable(velocityX+velocityY)).start(); } else { // the normal rotation // CircleLayout.this // .post(new FlingRunnable(velocityX + velocityY)); new Thread(new FlingRunnable(-(velocityX+velocityY))).start(); } return true; } @Override public boolean onSingleTapUp(MotionEvent e) { int cur = getInCircle((int)e.getX(),(int)e.getY()); if(cur!=-1){ if(mListener!=null){ mListener.onSingleTapUp(cur); } // Toast.makeText(getContext(), "position:"+cur, 0).show(); return true; } return false; } } private class FlingRunnable implements Runnable{ private float velocity; public FlingRunnable(float velocity){ this.velocity = velocity; } @Override public void run() { // TODO Auto-generated method stub if(Math.abs(velocity)>=200){ Message message = Message.obtain(); message.what = TO_ROTATE_BUTTON; message.obj = velocity; handler.sendMessage(message); } } } /** * @return The selected quadrant. */ private static int getQuadrant(double x, double y) { if (x >= 0) { return y >= 0 ? 1 : 4; } else { } return y >= 0 ? 2 : 3; } /* * 旋轉選單按鈕 */ private void rotateButtons(double degree) { for (int i = 0; i < STONE_COUNT; i++) { mStones[i].angle -= degree; if (mStones[i].angle < 0) { mStones[i].angle += 360; }else if(mStones[i].angle >=360){ mStones[i].angle -= 360; } } computeCoordinates(); invalidate(); } @Override public void onDraw(Canvas canvas) { //畫一個白色的圓環 canvas.drawCircle(mPointX, mPointY, mRadius, mPaint); //將每個選單畫出來 for (int index = 0; index < STONE_COUNT; index++) { if (!mStones[index].isVisible) continue; drawInCenter(canvas, mStones[index].bitmap, mStones[index].x, mStones[index].y); } } /** * 把中心點放到中心處 * * @param canvas * @param bitmap * @param left * @param top */ private void drawInCenter(Canvas canvas, Bitmap bitmap, float left, float top) { Rect dst = new Rect(); dst.left = (int) (left - menuRadius); dst.right = (int) (left + menuRadius); dst.top = (int) (top - menuRadius); dst.bottom = (int) (top + menuRadius); canvas.setDrawFilter(pfd); canvas.drawBitmap(bitmap, null, dst, mPaint); } private int getInCircle(int x, int y) { for (int i = 0; i < STONE_COUNT; i++) { BigStone stone = mStones[i]; int mx = (int) stone.x; int my = (int) stone.y; if (((x - mx) * (x - mx) + (y - my) * (y - my)) < menuRadius * menuRadius) { return i; } } return -1; } public void setOnRoundSpinViewListener(onRoundSpinViewListener listener){ this.mListener = listener; } class BigStone { // 圖片 Bitmap bitmap; // 角度 int angle; // x座標 float x; // y座標 float y; // 是否可見 boolean isVisible = true; } }
注意:必須加上這一條 :<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.example.roundspinviewdemo.view.RoundSpinView android:id="@+id/rsv_test" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:background="@drawable/menubkground" app:menuStart="@drawable/menu1" /> </LinearLayout>
xmlns:app="http://schemas.android.com/apk/res-auto"
此外必須新增attr檔案設定對應的自定義屬性:
接下來就是activity中的應用了:<?xml version="1.0" encoding="utf-8"?> <resources> <!-- 設定旋轉選單對應的第一張圖片 --> <declare-styleable name="RoundSpinView"> <attr name="menuStart" format="reference" /> </declare-styleable> </resources>
public class MainActivity extends Activity implements onRoundSpinViewListener {
private RoundSpinView rsv_test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
rsv_test = (RoundSpinView)this.findViewById(R.id.rsv_test);
rsv_test.setOnRoundSpinViewListener(this);
}
@Override
public void onSingleTapUp(int position) {
// TODO Auto-generated method stub
switch (position) {
case 0:
Toast.makeText(MainActivity.this, "place:0", 0).show();
break;
case 1:
Toast.makeText(MainActivity.this, "place:1", 0).show();
break;
case 2:
Toast.makeText(MainActivity.this, "place:2", 0).show();
break;
default:
break;
}
}
}
注意:rsv_test.setOnRoundSpinViewListener(this);
對自定義view的自定義監聽器進行賦值
至此,你的專案就可以擁有看上去很高大上的旋轉換位選單功能
這裡附上此demo對應的資源連結:點選開啟連結