Android 自定義滑動解鎖View
阿新 • • 發佈:2019-02-01
package com.inks.jisaimedicalforch8.view; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color;import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; importandroid.util.AttributeSet; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Interpolator; import com.inks.inkslibrary.utils.L;import com.inks.jisaimedicalforch8.UI.R; /** * Created by inks on 2018/6/29 0029. */ public class SlideUnlockView extends View { public interface UnlockListener { void onUnlock(); } private UnlockListener mUnlockListener; public void setUnlockListener(UnlockListener unlockListener) { mUnlockListener = unlockListener; } private static final int MSG_REDRAW = 1; private static final int DRAW_INTERVAL = 50; private static final int STEP_LENGTH = 10;//速度 private Paint mPaint;//文字的畫筆 private Paint mSliPaint;//滑塊畫筆 private Paint mBgPaint;//背景畫筆 private VelocityTracker mVelocityTracker;//滑動速度 private int mMaxVelocity; private LinearGradient mGradient;//漸變色 private LinearGradient bgGradient;//背景漸變色 private LinearGradient sliGradient;//滑塊漸變色 // LinearGradient有兩個建構函式; // // public LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions,Shader.TileMode tile) // // 引數: // // float x0: 漸變起始點x座標 // // float y0:漸變起始點y座標 // // float x1:漸變結束點x座標 // // float y1:漸變結束點y座標 // // int[] colors:顏色 的int 陣列 // // float[] positions: 相對位置的顏色陣列,可為null, 若為null,可為null,顏色沿漸變線均勻分佈 // // Shader.TileMode tile: 渲染器平鋪模式 // // // // public LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1,Shader.TileMode tile) // // float x0: 漸變起始點x座標 // // float y0:漸變起始點y座標 // // float x1:漸變結束點x座標 // // float y1:漸變結束點y座標 // // int color0: 起始漸變色 // int color1: 結束漸變色 // // Shader.TileMode tile: 渲染器平鋪模式 private int[] mGradientColors; private int[] bgGradientColors; private int mGradientIndex; private Interpolator mInterpolator; private float mDensity; private Matrix mMatrix; private ValueAnimator mValueAnimator; private int width; private int height; private String mText;//文字 private int mTextSize;//文字大小 private int mTextLeft;//文字距離左邊 private int mR;//滑塊的半徑 private float margin; private Rect mSliderRect; private int mSlidableLength; // SlidableLength = BackgroundWidth - LeftMagins - RightMagins - SliderWidth private int mEffectiveLength; // Suggested length is 20pixels shorter than SlidableLength private float mEffectiveVelocity = 1000;//滑塊自動回滾的速度 private float mStartX; private float mStartY; private float mLastX; private float mMoveX; public SlideUnlockView(Context context) { this(context, null); } public SlideUnlockView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SlideUnlockView(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public SlideUnlockView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); mDensity = getResources().getDisplayMetrics().density; ViewConfiguration configuration = ViewConfiguration.get(context); mMaxVelocity = configuration.getScaledMaximumFlingVelocity(); mInterpolator = new AccelerateDecelerateInterpolator(); setClickable(true); setFocusable(true); setFocusableInTouchMode(true); mSlidableLength = 200; mText = ">> 滑動進入主頁"; mTextSize = 36;//文字大小 mTextLeft = 50;//文字距離左邊 mMoveX = 0; mGradientIndex = 0; mSliPaint = new Paint(); mSliPaint.setAntiAlias(true); mBgPaint = new Paint(); mBgPaint.setAntiAlias(true); mPaint = new Paint(); mPaint.setTextSize(mTextSize); //該方法即為設定基線上那個點究竟是left,center,還是right mPaint.setTextAlign(Paint.Align.LEFT); // mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int specWidthSize = MeasureSpec.getSize(widthMeasureSpec);//寬 int specHeightSize = MeasureSpec.getSize(heightMeasureSpec);//高 mMatrix = new Matrix(); width = specWidthSize; height = specHeightSize; mTextLeft = (int) (height * 1.5); margin = height / 20; mR = (int) (((height-margin*2) / 2)-margin); mSlidableLength = (int) (specWidthSize -mR*2-margin*4); mEffectiveLength = mSlidableLength-20; mSliderRect = new Rect((int) margin,(int) margin, (int) (mR*2+ margin*2), (int) (mR*2+ margin*2)); mGradientColors = new int[]{Color.argb(255, 120, 120, 120), Color.argb(255, 120, 120, 120), Color.argb(255, 255, 255, 255)}; mGradient = new LinearGradient(0, 0, width/2, 0, mGradientColors, new float[]{0, 0.7f, 1}, Shader.TileMode.MIRROR); bgGradient = new LinearGradient( 0, 0, 0, (float) ((height)/2.0), Color.argb(80, 0X77, 0X77, 0X77), Color.argb(200, 0X11, 0X11, 0X11), Shader.TileMode.CLAMP ); sliGradient = new LinearGradient( 0, 0, 0, (float) ((height)/2.0), Color.argb(80, 0Xbb, 0Xbb, 0Xbb), Color.argb(200, 0X77, 0X77, 0X77), Shader.TileMode.CLAMP ); // bgGradientColors = new int[]{Color.argb(80, 0X77, 0X77, 0X77), // Color.argb(200, 0X11, 0X11, 0X11), Color.argb(80, 0X77, 0X77, 0X77)}; // bgGradient = new LinearGradient(margin, 0, margin, height-margin, bgGradientColors, // new float[]{0, 0.5f, 1}, Shader.TileMode.MIRROR); mBgPaint.setShader(bgGradient); mSliPaint.setShader(sliGradient); mHandler.removeMessages(MSG_REDRAW); mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); RectF oval = new RectF(margin, margin, width - margin, height - margin);// 設定個新的長方形 canvas.drawRoundRect(oval, (float) ((height - margin*2)/2.0), (float) ((height - margin*2)/2.0), mBgPaint);//第二個引數是x半徑,第三個引數是y半徑 mPaint.setShader(mGradient); Paint.FontMetrics fontMetrics = mPaint.getFontMetrics(); float top = fontMetrics.top;//為基線到字型上邊框的距離 float bottom = fontMetrics.bottom;//為基線到字型下邊框的距離 int baseLineY = (int) (height / 2 - top / 2 - bottom / 2);//基線中間點的y軸計算公式 canvas.drawText(mText, mTextLeft, baseLineY, mPaint); canvas.drawCircle(mR + mMoveX+margin*2, height/2, mR, mSliPaint); } public void reset() { if (mValueAnimator != null) { mValueAnimator.cancel(); } mMoveX = 0; mPaint.setAlpha(255); mHandler.removeMessages(MSG_REDRAW); mHandler.sendEmptyMessageDelayed(MSG_REDRAW,200); } @Override public boolean onTouchEvent(MotionEvent event) { L.e(event.getAction()+""); // 點選是否在滑塊上 if (event.getAction() != MotionEvent.ACTION_DOWN && !mSliderRect.contains((int) mStartX, (int) mStartY)) { if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) { mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL); } return super.onTouchEvent(event); } acquireVelocityTrackerAndAddMovement(event); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mStartX = event.getX(); mStartY = event.getY(); mLastX = mStartX; mHandler.removeMessages(MSG_REDRAW); L.e("按下"); break; case MotionEvent.ACTION_MOVE: L.e("移動"); mLastX = event.getX(); if (mLastX > mStartX) { int alpha = (int) (255 - (mLastX - mStartX) * 3 / mDensity); if (alpha > 1) { mPaint.setAlpha(alpha); } else { mPaint.setAlpha(0); } if (mLastX - mStartX > mSlidableLength) { mLastX = mStartX + mSlidableLength; mMoveX = mSlidableLength; } else { mMoveX = (int) (mLastX - mStartX); } } else { mLastX = mStartX; mMoveX = 0; } invalidate(); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: L.e("擡起或超出"); mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity); float velocityX = mVelocityTracker.getXVelocity(); L.e("速度"+velocityX); if (mLastX - mStartX > mEffectiveLength || velocityX/2 > mEffectiveVelocity) { startAnimator(mLastX - mStartX, mSlidableLength, velocityX, true); } else { startAnimator(mLastX - mStartX, 0, velocityX, false); mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL); } releaseVelocityTracker(); break; } return super.onTouchEvent(event); } private void startAnimator(float start, float end, float velocity, boolean isRightMoving) { if (velocity < mEffectiveVelocity) { velocity = mEffectiveVelocity; } int duration = (int) (Math.abs(end - start) * 1000 / velocity); mValueAnimator = ValueAnimator.ofFloat(start, end); mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mMoveX = (Float) animation.getAnimatedValue(); int alpha = (int) (255 - (mMoveX) * 3 / mDensity); if (alpha > 1) { mPaint.setAlpha(alpha); } else { mPaint.setAlpha(0); } invalidate(); } }); mValueAnimator.setDuration(duration); mValueAnimator.setInterpolator(mInterpolator); if (isRightMoving) { mValueAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { L.e("解鎖"); // reset(); if (mUnlockListener != null) { mUnlockListener.onUnlock(); } } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); } mValueAnimator.start(); } private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); } private void releaseVelocityTracker() { if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case MSG_REDRAW: if(mMatrix==null){ mMatrix = new Matrix(); } mMatrix.setTranslate(mGradientIndex, 0); if(mGradient==null){ L.e("mGradient空"); mGradientColors = new int[]{Color.argb(255, 120, 120, 120), Color.argb(255, 120, 120, 120), Color.argb(255, 255, 255, 255)}; mGradient = new LinearGradient(0, 0, width/2, 0, mGradientColors, new float[]{0, 0.7f, 1}, Shader.TileMode.MIRROR); } mGradient.setLocalMatrix(mMatrix); invalidate(); mGradientIndex += STEP_LENGTH ; if(mGradientIndex>=Integer.MAX_VALUE){ mGradientIndex = 0; } mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL); break; } } }; }
<com.inks.jisaimedicalforch8.view.SlideUnlockView android:id="@+id/SlideUnlockView" android:layout_width="550dp" android:layout_height="100dp" android:layout_centerHorizontal="true" android:layout_marginTop="750dp" />