短视频源码PHP实现手势密码的方法

具体实现过程
下面讲下实现的过程,如果只是直接拿来用的话也可以略过这部分。

自定义手势密码的圆形view
这部分主要参考Hongyang大大的博客,稍微修改了一下

初始化传入参数

public GestureLockView(Context context, int colorNoFingerr, int colorFingerOn, int colorCorrect, int colorError) {        super(context);        this.mColorNoFinger = colorNoFingerr;        this.mColorFingerOn = colorFingerOn;        this.mColorFingerUpCorrect = colorCorrect;        this.mColorFingerUpError = colorError;
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mArrowPath = new Path();
    }

根据不同的触摸状态绘制不同颜色的圆

@Override
    protected void onDraw(Canvas canvas) {        switch (mCurrentStatus) {            case STATUS_FINGER_ON:                // 绘制外圆
                mPaint.setStyle(Style.STROKE);
                mPaint.setColor(mColorFingerOn);
                mPaint.setStrokeWidth(2);
                canvas.drawCircle(mCenterX, mCenterY, mRadius, mPaint);                // 绘制内圆
                mPaint.setStyle(Style.FILL);
                canvas.drawCircle(mCenterX, mCenterY, mRadius * mInnerCircleRadiusRate, mPaint);                break;            case STATUS_FINGER_UP:                // 绘制外圆
                if (GestureLockViewGroup.isCorrect)
                    mPaint.setColor(mColorFingerUpCorrect);                else
                    mPaint.setColor(mColorFingerUpError);
                mPaint.setStyle(Style.STROKE);
                mPaint.setStrokeWidth(2);
                canvas.drawCircle(mCenterX, mCenterY, mRadius, mPaint);                // 绘制内圆
                mPaint.setStyle(Style.FILL);
                canvas.drawCircle(mCenterX, mCenterY, mRadius * mInnerCircleRadiusRate, mPaint);
                drawArrow(canvas);                break;            case STATUS_NO_FINGER:                // 绘制外圆
                mPaint.setStyle(Style.STROKE);
                mPaint.setColor(mColorNoFinger);
                canvas.drawCircle(mCenterX, mCenterY, mRadius, mPaint);                // 绘制内圆
                mPaint.setStyle(Style.FILL);
                mPaint.setColor(mColorNoFinger);
                canvas.drawCircle(mCenterX, mCenterY, mRadius * mInnerCircleRadiusRate, mPaint);                break;
        }
    }

绘制箭头

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        mWidth = MeasureSpec.getSize(widthMeasureSpec);
        mHeight = MeasureSpec.getSize(heightMeasureSpec);        // 取长和宽中的小值
        mWidth = mWidth < mHeight ? mWidth : mHeight;
        mRadius = mCenterX = mCenterY = mWidth / 2;
        mRadius -= mStrokeWidth / 2;        // 绘制三角形,初始时是个默认箭头朝上的一个等腰三角形,用户绘制结束后,根据由两个GestureLockView决定需要旋转多少度
        float mArrowLength = mWidth / 2 * mArrowRate;
        mArrowPath.moveTo(mWidth / 2, mStrokeWidth + 2);
        mArrowPath.lineTo(mWidth / 2 - mArrowLength, mStrokeWidth + 2 + mArrowLength);
        mArrowPath.lineTo(mWidth / 2 + mArrowLength, mStrokeWidth + 2 + mArrowLength);
        mArrowPath.close();
        mArrowPath.setFillType(Path.FillType.WINDING);
    } private void drawArrow(Canvas canvas) {        if (mArrowDegree != -1) {
            mPaint.setStyle(Paint.Style.FILL);

            canvas.save();
            canvas.rotate(mArrowDegree, mCenterX, mCenterY);
            canvas.drawPath(mArrowPath, mPaint);
            canvas.restore();
        }
    }

自定义手势密码的ViewGroup
加入自定义view的属性

<?xml version="1.0" encoding="utf-8"?><resources>

    <attr name="color_no_finger" format="color" />
    <attr name="color_finger_on" format="color" />
    <attr name="color_finger_up_correct" format="color" />
    <attr name="color_finger_up_error" format="color" />
    <attr name="count" format="integer" />
    <attr name="preference_id" format="integer" />

    <declare-styleable name="GestureLockViewGroup">
        <attr name="color_no_finger" />
        <attr name="color_finger_on" />
        <attr name="color_finger_up_correct" />
        <attr name="color_finger_up_error" />
        <attr name="count" />
        <attr name="preference_id" />
    </declare-styleable></resources>

获取参数及初始化

public GestureLockViewGroup(Context context, AttributeSet attrs,                                int defStyle) {
        super(context, attrs, defStyle);        /**
         * 获得所有自定义的参数的值
         */
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.GestureLockViewGroup, defStyle, 0);

        mNoFingerColor = a.getColor(R.styleable.GestureLockViewGroup_color_no_finger, mNoFingerColor);
        mFingerOnColor = a.getColor(R.styleable.GestureLockViewGroup_color_finger_on, mFingerOnColor);
        mFingerUpColorCorrect = a.getColor(R.styleable.GestureLockViewGroup_color_finger_up_correct, mFingerUpColorCorrect);
        mFingerUpColorError = a.getColor(R.styleable.GestureLockViewGroup_color_finger_up_error, mFingerUpColorError);
        mCount = a.getInt(R.styleable.GestureLockViewGroup_count, mCount);
        mPrferenceId = a.getInt(R.styleable.GestureLockViewGroup_preference_id, mPrferenceId);

        a.recycle();        /**
         * 获取密码状态
         */
        gesturePreference = new GesturePreference(context, mPrferenceId);
        password = gesturePreference.ReadStringPreference();
        Log.d(TAG, "password now is : " + password);
        isSetPassword = !password.equals("null"); //判断是否已经保存有密码
        isInPasswordSettingMode = !isSetPassword;     //当未设置密码,进入密码设置模式

        // 初始化画笔
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPath = new Path();
    }

根据参数绘制出圆
在onMeasure后调用该方法,绘制圆形矩阵

private GestureLockView[] mGestureLockViews; //保存所有的GestureLockViewprivate void initViews() {        // 初始化mGestureLockViews
        if (mGestureLockViews == null) {
            mGestureLockViews = new GestureLockView[mCount * mCount];            // 计算每个GestureLockView的宽度
            mGestureLockViewWidth = (int) (4 * mWidth * 1.0f / (5 * mCount + 1));            //计算每个GestureLockView的间距
            mMarginBetweenLockView = (int) (mGestureLockViewWidth * 0.25);            // 设置画笔的宽度为GestureLockView的内圆直径稍微小点
            mPaint.setStrokeWidth(mGestureLockViewWidth * 0.29f);            for (int i = 0; i < mGestureLockViews.length; i++) {                //初始化每个GestureLockView
                mGestureLockViews[i] = new GestureLockView(getContext(), mNoFingerColor, mFingerOnColor, mFingerUpColorCorrect, mFingerUpColorError);
                mGestureLockViews[i].setId(i + 1);                //设置参数,主要是定位GestureLockView间的位置
                RelativeLayout.LayoutParams lockerParams = new RelativeLayout.LayoutParams(
                        mGestureLockViewWidth, mGestureLockViewWidth);                // 不是每行的第一个,则设置位置为前一个的右边
                if (i % mCount != 0) {
                    lockerParams.addRule(RelativeLayout.RIGHT_OF,
                            mGestureLockViews[i - 1].getId());
                }                // 从第二行开始,设置为上一行同一位置View的下面
                if (i > mCount - 1) {
                    lockerParams.addRule(RelativeLayout.BELOW,
                            mGestureLockViews[i - mCount].getId());
                }                //设置右下左上的边距
                int rightMargin = mMarginBetweenLockView;                int bottomMargin = mMarginBetweenLockView;                int leftMagin = 0;                int topMargin = 0;                /**
                 * 每个View都有右外边距和底外边距 第一行的有上外边距 第一列的有左外边距
                 */
                if (i >= 0 && i < mCount)// 第一行
                {
                    topMargin = mMarginBetweenLockView;
                }                if (i % mCount == 0)// 第一列
                {
                    leftMagin = mMarginBetweenLockView;
                }

                lockerParams.setMargins(leftMagin, topMargin, rightMargin,
                        bottomMargin);
                mGestureLockViews[i].setMode(Mode.STATUS_NO_FINGER);
                addView(mGestureLockViews[i], lockerParams);
            }
        }
    }

在触摸监听中处理不同事件

 @Override    public boolean onTouchEvent(MotionEvent event) {        int action = event.getAction();        int x = (int) event.getX();        int y = (int) event.getY();
        Log.d(TAG, "mTryTimes : " + mTryTimes);        //重试次数超过限制,直接返回
        if (mTryTimes <= 0 && isRetryTimeLimit) { 
            return true;
        }        switch (action) {            case MotionEvent.ACTION_DOWN:
                reset();     // 重置
                break;            case MotionEvent.ACTION_MOVE:
                drawAndGetSelectedWhenTouchMove(x, y);                break;            case MotionEvent.ACTION_UP:                if (isInPasswordSettingMode) {                    if (gesturePasswordSettingListener != null)
                        setPasswordHandle();  //设置密码
                } else {                    if (mChoose.size() > 0) {
                        isCorrect = checkAnswer();
                    } else {                        return true;
                    }                    if (gestureEventListener != null) {
                        gestureEventListener.onGestureEvent(isCorrect);  //将结果回调
                    }                    if (this.mTryTimes == 0) {
                        gestureUnmatchedExceedListener.onUnmatchedExceedBoundary();  //超出重试次数,进入回调
                    }
                }
                drawWhenTouchUp();                break;
        }
        invalidate();        return true;
    } private void drawAndGetSelectedWhenTouchMove(int x, int y) {
        mPaint.setColor(mFingerOnColor);
        mPaint.setAlpha(50);
        GestureLockView child = getChildIdByPos(x, y);        if (child != null) {            int cId = child.getId();            if (!mChoose.contains(cId)) {
                mChoose.add(cId);
                mChooseString = mChooseString + cId;
                child.setMode(Mode.STATUS_FINGER_ON);                // 设置指引线的起点
                mLastPathX = child.getLeft() / 2 + child.getRight() / 2;
                mLastPathY = child.getTop() / 2 + child.getBottom() / 2;                if (mChoose.size() == 1)// 当前添加为第一个
                {
                    mPath.moveTo(mLastPathX, mLastPathY);
                } else
                // 非第一个,将两者使用线连上
                {
                    mPath.lineTo(mLastPathX, mLastPathY);
                }
            }
        }        // 指引线的终点
        mTmpTarget.x = x;
        mTmpTarget.y = y;
    }    private void drawWhenTouchUp() {        if (isCorrect) {
            mPaint.setColor(mFingerUpColorCorrect);
        } else {
            mPaint.setColor(mFingerUpColorError);
        }
        mPaint.setAlpha(50);
        Log.d(TAG, "mChoose = " + mChoose);        // 将终点设置位置为起点,即取消指引线
        mTmpTarget.x = mLastPathX;
        mTmpTarget.y = mLastPathY;        // 改变子元素的状态为UP
        setItemModeUp();        // 计算每个元素中箭头需要旋转的角度
        for (int i = 0; i + 1 < mChoose.size(); i++) {            int childId = mChoose.get(i);            int nextChildId = mChoose.get(i + 1);

            GestureLockView startChild = (GestureLockView) findViewById(childId);
            GestureLockView nextChild = (GestureLockView) findViewById(nextChildId);            int dx = nextChild.getLeft() - startChild.getLeft();            int dy = nextChild.getTop() - startChild.getTop();            // 计算角度
            int angle = (int) Math.toDegrees(Math.atan2(dy, dx)) + 90;
            startChild.setArrowDegree(angle);
        }
    }

设置密码处理:

private void setPasswordHandle() {        if (isWaitForFirstInput) {            if (gesturePasswordSettingListener.onFirstInputComplete(mChooseString.length())) {
                firstInputPassword = mChooseString;
                isWaitForFirstInput = false;
            }
        } else {            if (firstInputPassword.equals(mChooseString)) {
                gesturePasswordSettingListener.onSuccess();
                savePassword(mChooseString);
                isInPasswordSettingMode = false;
            } else {
                gesturePasswordSettingListener.onFail();
            }
        }
        reset();
    }

检查手势密码是否正确:

public boolean checkAnswer() {        if (password.equals(mChooseString)) {            return true;
        } else {            if (isRetryTimeLimit)                this.mTryTimes--;            return false;
        }
    }

重置:

private void reset() {
        mChoose.clear();
        mChooseString = "";
        mPath.reset();        for (GestureLockView gestureLockView : mGestureLockViews) {
            gestureLockView.setMode(Mode.STATUS_NO_FINGER);
            gestureLockView.setArrowDegree(-1);
        }
    }

对外公开的一些方法

public void setGestureEventListener(GestureEventListener gestureEventListener) {        this.gestureEventListener = gestureEventListener;
    }    public void setGestureUnmatchedExceedListener(int retryTimes, GestureUnmatchedExceedListener gestureUnmatchedExceedListener) {
        isRetryTimeLimit = true;        this.mTryTimes = retryTimes;        this.gestureUnmatchedExceedListener = gestureUnmatchedExceedListener;
    }    public void setGesturePasswordSettingListener(GesturePasswordSettingListener gesturePasswordSettingListener) {        this.gesturePasswordSettingListener = gesturePasswordSettingListener;
    }    public void removePassword() {
        gesturePreference.WriteStringPreference("null");        this.isSetPassword = false;
        isWaitForFirstInput = true;
        isInPasswordSettingMode = true;
    }    public void savePassword(String password) {        this.password = password;
        gesturePreference.WriteStringPreference(password);
    }    public String getPassword() {        return password;
    }    public void resetView() {
        reset();
        invalidate();
    }    public void setRetryTimes(int retryTimes) {        this.mTryTimes = retryTimes;
    }    public boolean isSetPassword() {        return isSetPassword;
    }

定义密码存储的Preference
就是简单的存和读

public GesturePreference(Context context, int nameTableId) {        this.context = context;        if (nameTableId != -1)            this.nameTable = nameTable + nameTableId;
    }    public void WriteStringPreference(String data) {
        SharedPreferences preferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(nameTable, data);
        editor.commit();
    }    public String ReadStringPreference() {
        SharedPreferences preferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);        return preferences.getString(nameTable, "null");
    }
发布了151 篇原创文章 · 获赞 65 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/yb1314111/article/details/105386350