仿遥控器菜单圆盘
1.效果
2.github地址
github地址
https://github.com/caixingcun/CopyMenu
3.前言
之前有一家面试,有这么一个需求,问我需要如何实现这么一个效果
刚开始感觉相对布局什么也能实现差不多的,但面试官提问到如何处理重叠部分
之后回答说自定义控件,因为自定义控件写的少,也就只有个大概思路
一带而过了,回来花了点时间,搞出来,跟大家分享下,也是来扩充博客
4.原理
这样的需要主要麻烦的地方是在点击后,响应特定区块
如果只是单纯画图 和 点击对应区域回调,完全可以画同心圆 和 线来实现
这里是将每一个区块的线上的点计算出来 连成path
创建特定标志位记录点击区域,重绘区块实现区块变色
5.代码
step1.创建一个类继承View,创建构造函数,在构造中初始化自定义属性 和 画笔
public class MenuView extends View
public MenuView(Context context) {
this(context, null);
}
public MenuView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MenuView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//获取自定义属性。
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.menuview);
//获取字体大小,默认大小是16dp
mLineColor = ta.getColor(R.styleable.menuview_lineColor, Color.BLACK);
mArrowColor = ta.getColor(R.styleable.menuview_arrowColor, Color.BLACK);
mChoseColor = ta.getColor(R.styleable.menuview_choseColor, Color.BLACK);
mArrowChoseColor = ta.getColor(R.styleable.menuview_arrowChoseColor, Color.WHITE);
mText = (String) ta.getText(R.styleable.menuview_mtext);
mTextSize = ta.getDimension(R.styleable.menuview_mtextSize, 30);
Log.d("tag", "mTextSize" + mTextSize);
ta.recycle();
mPaint = new Paint();
mPaint.setColor(mLineColor);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(2);//线宽
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setTextSize(mTextSize);
mPaint.setTypeface(Typeface.DEFAULT_BOLD);
}
step2.自定义属性 ,声明命名空间
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="menuview">
<!--线条颜色-->
<attr name="lineColor" format="color"/>
<!--箭头颜色-->
<attr name="arrowColor" format="color"/>
<!--选择反色-->
<attr name="choseColor" format="color"/>
<!--选择箭头反色-->
<attr name="arrowChoseColor" format="color"/>
<!--中间OK或者菜单字体大小-->
<attr name="mtextSize" format="dimension"/>
<!--中间文字内容-->
<attr name="mtext"