参考http://www.jfh.com/jfperiodical/article/3527?ref=myread?修改
效果图
代码
/** * Edit by lsj on 2019/10/10. */ @SuppressLint("AppCompatCustomView") public class PasswordView extends EditText { private static final String TAG ="PasswordView" ; private Paint bordPaint;//外框画笔 private Paint bgPaint;//背景画笔 private Paint linePaint;//线 的画笔 private Paint passTextPaint;//密码画笔 private float width; private float height; private int passwordLength = 6;//代码的长度 private int textLength; private int radius = 15; public PasswordView(Context context) { this(context,null); } public PasswordView(Context context, AttributeSet attrs) { this(context, attrs,0); } public PasswordView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initPaint(); } /** * 初始化画笔 */ private void initPaint() { setFocusable(true); bordPaint = new Paint(); bordPaint.setStrokeWidth(4); bordPaint.setColor(Color.parseColor("#cccccc")); bordPaint.setStyle(Paint.Style.STROKE); bgPaint = new Paint(); bgPaint.setStrokeWidth(4); bgPaint.setColor(Color.parseColor("#ffffff")); bgPaint.setStyle(Paint.Style.FILL); linePaint = new Paint(); linePaint.setColor(Color.parseColor("#eeeeee")); linePaint.setStrokeWidth(2); passTextPaint = new Paint(); passTextPaint.setColor(Color.parseColor("#000000")); passTextPaint.setStrokeWidth(12); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); height = getMeasuredHeight(); width = getMeasuredWidth(); drawRoundRect(canvas); drawLine(canvas); drawTextPass(canvas); } /** * 绘制密码 * @param canvas */ private void drawTextPass(Canvas canvas) { float cx, cy = height/ 2; float half = width / passwordLength / 2; for(int i = 0; i < textLength; i++) { cx = width * i / passwordLength + half; canvas.drawCircle(cx, cy, radius, passTextPaint); } } /** * 绘制线 * @param canvas */ private void drawLine(Canvas canvas) { for (int i = 1; i < passwordLength; i++) { float x = width * i / passwordLength; canvas.drawLine(x, 12, x, height-12, linePaint); } } /** * 绘制背景 * @param canvas */ private void drawRoundRect(Canvas canvas) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { canvas.drawRoundRect(2f,2f,width-2,height-2,14f,14f,bordPaint); canvas.drawRoundRect(2f,2f,width-2,height-2,14f,14f,bgPaint); } } @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); this.textLength = text.toString().length(); if(textLength==6){ Toast.makeText(getContext(),"您设置的密码为"+text, Toast.LENGTH_SHORT).show(); //自动提交密码处 } invalidate(); } public void setEmpeyText(){ setText(""); invalidate(); } }
使用时如下添加
修改部分添加外框。
收获:drawRoundRect绘制圆角时, 圆角矩形应该是基于矩形绘制的,当 mPaint.setStrokeWidth(5) 设置线宽为5,那么矩形的左上角的外边是从 (-2.5,-2.5)开始,内角是从(2.5,2.5)开始,加起来线宽是5。所以需调整划线的开始和结束为止。参考https://blog.csdn.net/kuaiguixs/article/details/78753149