Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圓形旋轉菜單實作:用三角函數讓菜單繞圈跑

編輯:關於 Android 程式設計

前陣子幫朋友做了一個動畫菜單,覺得實用性不錯,就在這裡分享出來。先看效果:

實作思路

從圖上不難看出,這幾個菜單是繞著中心點旋轉的。旋轉可以拆成兩層:背景旋轉與菜單旋轉。

背景層直接用旋轉動畫即可;菜單層則是沿著以中心為圓心的圓周分佈,因此只要根據旋轉角度算出該點在直角座標系中的位置,再擺放菜單就行:

x = r * cos(rotation * 3.14 / 180)、y = r * sin(rotation * 3.14 / 180)

結論:數學還是很重要的。

1. 自定義 View 並繼承 RelativeLayout

public class CircleMenuLayout extends RelativeLayout {

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

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

    /**
     * 初始化布局:把旋轉背景與中心定位點加入容器
     */
    public CircleMenuLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        menuitems = new ArrayList<View>();

        // 中心定位點
        centerview = new View(context);
        centerview.setId(ID_CENTER_VIEW);
        LayoutParams lp = new LayoutParams(0, 0);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        addView(centerview, lp);

        // 旋轉的背景
        progressBar = new ProgressBar(context);
        LayoutParams lp2 = new LayoutParams(dip2px(context, 90), dip2px(context, 90));
        lp2.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        addView(progressBar, lp2);
        progressBar.setIndeterminateDrawable(
                context.getResources().getDrawable(R.mipmap.icon_circle_menu));
    }
}

構造函式中先放入一個 0 尺寸的中心定位 View,後續所有菜單都以此為基準做相對定位;再放進旋轉用的背景圖。

2. 依傳入資料產生菜單初始位置

/**
 * 初始化菜單項
 * @param size 菜單數量
 * @param center_distance 分佈半徑
 */
public void initMenuItem(int size, int center_distance, String[] titles, int[] imgs) {
    radus = 360f / size;
    int width = dip2px(context, 50);   // 菜單寬度
    int height = dip2px(context, 50);  // 菜單高度

    for (int i = 0; i < size; i++) {
        int top = 0;
        int left = 0;
        // r * cos(a * 3.14 / 180)
        top  = -(int)(Math.sin(radus * i * 3.1415f / 180) * center_distance);
        left = -(int)(Math.cos(radus * i * 3.1415f / 180) * center_distance);

        LayoutParams lp = new LayoutParams(dip2px(context, 50), dip2px(context, 50));
        View view = layoutInflater.inflate(R.layout.item_circle_menu, this, false);
        view.setTag(i);
        TextView tvname = (TextView) view.findViewById(R.id.tv_name);
        ImageView ivimg = (ImageView) view.findViewById(R.id.img);
        tvname.setText(titles[i]);
        ivimg.setImageResource(imgs[i]);

        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isrun) {
                    tag = (int) v.getTag();
                    currentPosition = tag;
                    if (tag == 0) {
                        finishdus = -360;
                    } else if (tag == 1) {
                        finishdus = -120;
                    } else if (tag == 2) {
                        finishdus = -240;
                    }
                    // 依點擊位置判斷旋轉方向
                    LayoutParams lp = (LayoutParams) v.getLayoutParams();
                    int l = lp.leftMargin;
                    int t = lp.topMargin;
                    if (t > -dip2px(context, 5) && l > -dip2px(context, 5)) {
                        oldradus = 120f;
                        isright = false;
                    } else if (t > -dip2px(context, 5) && l < -dip2px(context, 5)) {
                        oldradus = 120f;
                        isright = true;
                    } else if (t < -dip2px(context, 5)) {
                        oldradus = 0f;
                    }
                    sub = 0;
                    circleMenu(8, dip2px(context, 45), oldradus, isright);
                }
            }
        });

        lp.addRule(RelativeLayout.BELOW, centerview.getId());
        lp.addRule(RelativeLayout.RIGHT_OF, centerview.getId());
        lp.setMargins(-width / 2 + top, -height / 2 + left, 0, 0);
        addView(view, lp);
        menuitems.add(view);
    }
    handler.postDelayed(runnable, 0);
}

依菜單數量均分 360 度,逐一算出每個項目的座標並加入容器,初始化就完成了。這裡的點擊位置判斷只針對 3 個菜單做了適配,其他數量需要自己調整或改成通用寫法。

3. 背景旋轉動畫

/**
 * 依角度旋轉菜單
 */
public void circleMenu(float offserradius, int center_distance, float d, boolean right) {
    if (oldradus != 0) {
        progressBar.clearAnimation();
        if (isright) {
            mRotateUpAnim = new RotateAnimation(bgdus, bgdus + 120,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            bgdus += 120;
        } else {
            mRotateUpAnim = new RotateAnimation(bgdus, bgdus - 120,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            bgdus -= 120;
        }
        lir = new LinearInterpolator();
        mRotateUpAnim.setDuration(350);
        mRotateUpAnim.setFillAfter(true);
        mRotateUpAnim.setInterpolator(lir);
        progressBar.startAnimation(mRotateUpAnim);
    }
    circleMenuItem(offserradius, center_distance, d, right);
}

4. 菜單旋轉

/**
 * 菜單旋轉:以圓周運動方式移動各項目
 */
public void circleMenuItem(float offserradius, int center_distance, float d, boolean right) {
    sub += offserradius;
    if (sub > d) {
        if (onMenuItemSelectedListener != null) {
            onMenuItemSelectedListener.onMenuItemOnclick(tag);
        }
        isrun = false;
        return;
    }
    if (right) {
        offsetradus -= offserradius;
    } else {
        offsetradus += offserradius;
    }

    int size = menuitems.size();
    int width = dip2px(context, 50);
    int height = dip2px(context, 50);

    for (int i = 0; i < size; i++) {
        if (Math.abs(sub - d) <= 8) {
            offsetradus = finishdus;
        }
        LayoutParams lp = (LayoutParams) menuitems.get(i).getLayoutParams();
        float ds = radus * i + offsetradus;
        int top  = -(int)(Math.sin(ds * 3.1415f / 180) * center_distance);
        int left = -(int)(Math.cos(ds * 3.1415f / 180) * center_distance);
        lp.setMargins(-width / 2 + top, -height / 2 + left, 0, 0);
        menuitems.get(i).requestLayout();
    }

    if (sub <= d) {
        isrun = true;
        offsetradus = offsetradus % 360;
        handler.postDelayed(runnable, 5);
    } else {
        if (onMenuItemSelectedListener != null) {
            onMenuItemSelectedListener.onMenuItemOnclick(tag);
        }
        isrun = false;
    }
}

關鍵在於:以初始化時每個項目所處的角度為基準,用 handler 每 5 毫秒遞增或遞減角度,再重新計算位置,動畫效果就出來了。

5. 外部指定當前菜單項

這個方法目前有明顯局限,僅針對 3 個項目:

/**
 * 設定旋轉到指定的菜單項
 * @param tag 目標索引
 */
public void setCurrentTag(int tag) {
    if (currentPosition == tag) {
        return;
    }
    if (tag == 0) {
        finishdus = -360;
    } else if (tag == 1) {
        finishdus = -120;
    } else if (tag == 2) {
        finishdus = -240;
    }

    if (currentPosition == 0) {
        if (tag == 1) { oldradus = 120f; isright = true; }
        else if (tag == 2) { oldradus = 120f; isright = false; }
    } else if (currentPosition == 1) {
        if (tag == 2) { oldradus = 120f; isright = true; }
        else if (tag == 0) { oldradus = 120f; isright = false; }
    } else if (currentPosition == 2) {
        if (tag == 0) { oldradus = 120f; isright = true; }
        else if (tag == 1) { oldradus = 120f; isright = false; }
    }

    currentPosition = tag;
    this.tag = tag;
    sub = 0;
    circleMenu(8, dip2px(context, 45), oldradus, isright);
}

6. 呼叫方式

(1)布局檔:

<com.ywl5320.circlemenu.CircleMenuLayout
    android:id="@+id/cml_menu"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="92dp"/>

(2)菜單項布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:padding="5dp"
    android:gravity="center">

    <ImageView
        android:id="@+id/img"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:scaleType="fitXY"/>

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="菜單項"
        android:textSize="9sp"
        android:gravity="center"
        android:textColor="#ffffff"/>
</LinearLayout>

(3)Activity 中呼叫:

cmlmenu = (CircleMenuLayout) findViewById(R.id.cml_menu);
btn = (Button) findViewById(R.id.btn);

cmlmenu.initDatas(titles, imgs);
cmlmenu.setOnMenuItemSelectedListener(new CircleMenuLayout.OnMenuItemSelectedListener() {
    @Override
    public void onMenuItemOnclick(int code) {
        if (code == 0) {
            Toast.makeText(MainActivity.this, "支付寶", Toast.LENGTH_SHORT).show();
        } else if (code == 1) {
            Toast.makeText(MainActivity.this, "銀聯", Toast.LENGTH_SHORT).show();
        } else if (code == 2) {
            Toast.makeText(MainActivity.this, "微信", Toast.LENGTH_SHORT).show();
        }
    }
});

可延伸的方向

三個菜單的旋轉效果到這裡就完成了。要提醒的是,這份程式碼是為 3 個項目量身寫的,若換成其他數量,finishdus 與方向判斷那幾段都需要改寫。更好的做法是把它抽象成「已知目前角度、目標角度,求最短旋轉路徑」的通用算法——這樣不論幾個項目都能沿用。自己動手改過一次,收穫會比直接複用大得多。

以上就是本次分享,若有疑問歡迎留言,我會及時回覆。也非常感謝大家對本站的支持!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved