快要過年了,在這里提前祝小伙伴們新年快樂!
新的一年,要多寫點有質量的技術博客,哈哈。
上個月寫了個自定義控件,也是我們項目的新需求,我就拿出來放在DEMO里,給大家參考一下,說實話這也是我自己正兒八經地寫自定義控件。以前沒寫過,應該是沒碰到需要自己來寫的需求,網上都有現成的,這就是開源的一點好處吧,哈哈。
先放上效果圖,可以用手指來觸摸滑動的轉盤(儀表盤):
演示.gif
松手后自動指向最近數據:
演示2.gif
- 首先,測量確定控件的寬高,在XML里面設置寬度就行了,高度在代碼里會直接設置為寬度的一半,這里寬度我設置為match_parent。
//只需要設置寬度即可,高度默認為寬度的一半
<com.zzm.zzmvp.ui.widget.FuelFillingView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10px"
android:layout_marginRight="10px"/>
- 測量設置寬高
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = measureWidth(widthMeasureSpec);
setMeasuredDimension(width, width/2);
}
//根據xml的設定獲取寬度
private int measureWidth(int measureSpec) {
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
//wrap_content
if (specMode == MeasureSpec.AT_MOST){
}
//match_parent或者精確值
else if (specMode == MeasureSpec.EXACTLY){
}
return specSize;
}
- 初始化各個變量,創建畫筆等對象
變量有圓弧的半徑,半圓內長刻度的等分份數,一個長刻度內的等分份數,文字的數組,圓弧對應的矩陣等,最重要的就是手指旋轉的角度,滑動的時候就是根據這個值來進行重繪。
我用了四個畫筆,分別用來畫默認的圓弧,選中的藍色扇形,白色的扇形還有文字。
在onSizeChanged(int w, int h, int oldw, int oldh)方法中確定控件最終的寬高,得到圓弧的半徑以及確定圓弧的矩陣。
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mViewWidth = w;
mViewHeight = h;
mRadius = mViewWidth / 2 - dpToPx(10);
mRadiusChoose = mViewWidth / 2;
mRadiusSmall = mRadius / 2 - dpToPx(3);
mRectFArc.set(-mRadius,-mRadius,mRadius,mRadius);
mRectFArcChoose.set(-mRadiusChoose,-mRadiusChoose,mRadiusChoose,mRadiusChoose);
mRectFArcSmall.set(-mRadiusSmall,-mRadiusSmall,mRadiusSmall,mRadiusSmall);
...
}
- 接下來就是繪制了,主要用到了畫布的中心位移,旋轉,坐標的轉換,計算觸摸點和中心點的角度,這個讓我又把勾股定理研究了一下午,哈哈。
- 滑動事件就是將觸摸的點轉換為畫布坐標,計算出角度后進行重繪。
代碼較長,就貼上全部代碼:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import com.zzm.zzmlibrary.utils.LogUtils;
import com.zzm.zzmvp.R;
/**
* Created by ZhongZiMing on 2016/12/21.
*/
public class FuelFillingView extends View {
private final float startAngle = 180; //圓弧起始角度
private final float sweepAngle = 180; //旋轉的角度
private int mViewWidth,mViewHeight; //控件的寬和高
private int mRadius; //默認圓弧半徑
private int mStrokeWidth; //默認圓弧寬度
private int mRadiusChoose;//藍色扇形半徑
private int mRadiusSmall;//白色扇形半徑
private int selectedColor; //選中狀態的顏色
private int unSelectedColor; //未選中狀態的顏色
private int backgroundColor; //背景顏色
private int mSection = 10; // 長刻度等分份數
private int mPortion = 5; // 一個長刻度等分份數
private int mScaleLongLenth; //長刻度相對圓心的長度
private int mScaleShortLenth; //短刻度相對圓心的長度
private String[] mTexts ; //長刻度上的文字數組
private String[] mTextsValue; //跟刻度數字對應的值
private Context mContext;
private Paint mPaintArc; //默認圓弧
private Paint mPaintArcChoose; //選中的藍色扇形
private Paint mPaintArcSmall; //內部白色扇形
private Paint mPaintText; //文字
private Path mPath;
private RectF mRectFArc; // 默認圓弧
private RectF mRectFArcChoose; // 藍色扇形
private RectF mRectFArcSmall; //白色扇形
private Rect mRectText; //月份
private RectF mRectFInnerArc; //文字
private Bitmap mBitmapCar; //小汽車
private Bitmap mBitmapPoint; //指針
private Matrix matrix ;
private float eventX ; //手指按下的X坐標
private float eventY ; //手指按下的Y坐標
private int mEvent = MotionEvent.ACTION_UP;
/**
* 旋轉的角度
*/
private float mSweepAngle = 90;
public FuelFillingView(Context context) {
this(context,null);
}
public FuelFillingView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public FuelFillingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext =context;
// TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FuelFillView, defStyleAttr, 0);
//添加attr屬性
// selectedColor = a.getColor(R.styleable.FuelFillView_arcColor, Color.parseColor("#52adff"));
// a.recycle();
init();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mViewWidth = w;
mViewHeight = h;
mRadius = mViewWidth / 2 - dpToPx(10);
mRadiusChoose = mViewWidth / 2;
mRadiusSmall = mRadius / 2 - dpToPx(3);
mRectFArc.set(-mRadius,-mRadius,mRadius,mRadius);
mRectFArcChoose.set(-mRadiusChoose,-mRadiusChoose,mRadiusChoose,mRadiusChoose);
mRectFArcSmall.set(-mRadiusSmall,-mRadiusSmall,mRadiusSmall,mRadiusSmall);
mPaintText.setTextSize(spToPx(12));
mPaintText.getTextBounds("0", 0, "0".length(), mRectText);
mRectFInnerArc.set(-mRadius+mScaleLongLenth+mRectText.height()+dpToPx(6),
-mRadius+mScaleLongLenth+mRectText.height()+dpToPx(6),
mRadius-mScaleLongLenth-mRectText.height()-dpToPx(6),
mRadius-mScaleLongLenth-mRectText.height()-dpToPx(6));
mBitmapCar = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.icon_car);
Bitmap mBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.pointer_icon);
//將指針進行縮放和旋轉進行適配
matrix.postScale(1.0f,((float) (mRadiusChoose-mRadiusSmall))/(float) mBitmap.getHeight());
matrix.postRotate(-90);
mBitmapPoint = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
if(!mBitmap.isRecycled()){
mBitmap.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = measureWidth(widthMeasureSpec);
setMeasuredDimension(width, width/2);
}
//根據xml的設定獲取寬度
private int measureWidth(int measureSpec) {
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
//wrap_content
if (specMode == MeasureSpec.AT_MOST){
}
//match_parent或者精確值
else if (specMode == MeasureSpec.EXACTLY){
}
return specSize;
}
private void init(){
matrix = new Matrix();
mStrokeWidth = dpToPx(1);
mScaleLongLenth = dpToPx(10);
mScaleShortLenth = mScaleLongLenth / 2;
selectedColor = Color.parseColor("#52adff");
unSelectedColor = Color.parseColor("#a1a5aa");
backgroundColor = Color.parseColor("#ffffff");
mTexts = new String[]{"","及時充","","3個月","","6個月","","12個月","","24個月",""};
mTextsValue = new String[]{"","0折","","9.8折","","9.7折","","9.6折","","9.5折",""};
mPaintArc = new Paint();
mPaintArc.setAntiAlias(true);
mPaintArc.setColor(selectedColor);
mPaintArc.setStrokeWidth(mStrokeWidth);
mPaintArc.setStyle(Paint.Style.STROKE);
mPaintArc.setStrokeCap(Paint.Cap.ROUND);
mPaintArcChoose = new Paint();
mPaintArcChoose.setAntiAlias(true);
mPaintArcChoose.setColor(Color.parseColor("#3352adff"));
mPaintArcChoose.setStrokeCap(Paint.Cap.ROUND);
mPaintArcSmall = new Paint();
mPaintArcSmall.setAntiAlias(true);
mPaintArcSmall.setColor(backgroundColor);
mPaintArcSmall.setStrokeCap(Paint.Cap.ROUND);
mPaintText = new Paint();
mPaintText.setAntiAlias(true);
mPaintText.setStyle(Paint.Style.FILL);
mRectFArc = new RectF();
mRectFArcChoose = new RectF();
mRectFArcSmall = new RectF();
mRectText = new Rect();
mRectFInnerArc = new RectF();
mPath = new Path();
setBackgroundColor(backgroundColor);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mEvent = event.getAction();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
//此處使用 getRawX,而不是 getX
eventX = event.getRawX();
eventY = event.getRawY();
invalidate();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
//讓指針指向最近的數據,不需要則可注釋
float surplus = mSweepAngle % (sweepAngle / mSection);
int num = (int)((mSweepAngle - surplus) / (sweepAngle / mSection));
if(TextUtils.isEmpty(mTexts[num])&&!TextUtils.isEmpty(mTexts[num+1])){
mSweepAngle = mSweepAngle + (sweepAngle / mSection) - surplus;
}else if(!TextUtils.isEmpty(mTexts[num])){
mSweepAngle = mSweepAngle - surplus;
}
invalidate();
break;
}
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float[] pts = {eventX,eventY};
canvas.translate(mViewWidth/2,mViewHeight);//將畫布中心移動到控件底部中間
if(mEvent==MotionEvent.ACTION_DOWN||mEvent==MotionEvent.ACTION_MOVE){
changeCanvasXY(canvas,pts);//觸摸點的坐標轉換
}
drawArc(canvas);//畫選中的圓弧和未被選中的圓弧
drawLongLenth(canvas);//畫選中和未選中的長刻度
drawShortLenth(canvas);//畫選中和未選中的短刻度
drawText(canvas);//畫刻度上的文字
drawBlueArc(canvas);//畫選中的藍色扇形
drawPoint(canvas); //畫指針
drawWhiteArc(canvas);//畫內部白色扇形
drawCar(canvas);//畫小汽車
drawValue(canvas); //畫折扣價
}
private void changeCanvasXY(Canvas canvas,float[] pts){
// 獲得當前矩陣的逆矩陣
Matrix invertMatrix = new Matrix();
canvas.getMatrix().invert(invertMatrix);
// 使用 mapPoints 將觸摸位置轉換為畫布坐標
invertMatrix.mapPoints(pts);
float x = Math.abs(pts[0]);
float y = Math.abs(pts[1]);
double z = Math.sqrt(x*x+y*y);
float round = (float)(Math.asin(y/z)/Math.PI*180);
LogUtils.e("觸摸的點:X==="+pts[0]+"Y==="+pts[1]+"===當前角度:"+round);
if(pts[0]<=0){
mSweepAngle = round;
}else{
mSweepAngle = sweepAngle - round;
}
}
private void drawArc(Canvas canvas) {
mPaintArc.setColor(selectedColor);
canvas.drawArc(mRectFArc,startAngle,mSweepAngle,false,mPaintArc);
mPaintArc.setColor(unSelectedColor);
canvas.drawArc(mRectFArc,startAngle+mSweepAngle,sweepAngle-mSweepAngle,false,mPaintArc);
canvas.save();
}
private void drawLongLenth(Canvas canvas) {
float x0 = (float) (- mRadius + mStrokeWidth);
float x1 = (float) (- mRadius + mStrokeWidth + mScaleLongLenth);
mPaintArc.setStrokeWidth(mStrokeWidth*2);
mPaintArc.setColor(selectedColor);
canvas.drawLine(x0, 0, x1, 0, mPaintArc);
float angle = sweepAngle * 1f / mSection;
mPaintArc.setStrokeWidth(mStrokeWidth);
float selectSection = mSweepAngle / (sweepAngle / mSection);
for (int i = 1; i <= selectSection; i++) {
canvas.rotate(angle, 0, 0);
canvas.drawLine(x0, 0, x1, 0, mPaintArc);
}
mPaintArc.setColor(unSelectedColor);
for (int i = 0; i < mSection - selectSection; i++) {
if(i == mSection - (int)selectSection - 1){
mPaintArc.setStrokeWidth(mStrokeWidth*2);
}
canvas.rotate(angle, 0, 0);
canvas.drawLine(x0, 0, x1, 0, mPaintArc);
}
canvas.restore();
}
private void drawShortLenth(Canvas canvas) {
canvas.save();
mPaintArc.setStrokeWidth(mStrokeWidth/2);
mPaintArc.setColor(selectedColor);
float x0 = (float) (- mRadius + mStrokeWidth);
float x2 = (float) (- mRadius + mStrokeWidth + mScaleShortLenth);
canvas.drawLine(x0, 0, x2, 0, mPaintArc);
float angle = sweepAngle * 1f / (mSection*mPortion);
float mSelectSection = mSweepAngle / (sweepAngle / (mSection*mPortion));
for (int i = 1; i <= mSelectSection ; i++) {
canvas.rotate(angle, 0, 0);
canvas.drawLine(x0, 0, x2, 0, mPaintArc);
}
mPaintArc.setColor(unSelectedColor);
for (int i = 1; i <= (mSection * mPortion - mSelectSection); i++) {
canvas.rotate(angle, 0, 0);
canvas.drawLine(x0, 0, x2, 0, mPaintArc);
}
canvas.restore();
}
private void drawText(Canvas canvas) {
mPaintText.setTextSize(spToPx(12));
mPaintText.setTextAlign(Paint.Align.LEFT);
mPaintText.setTypeface(Typeface.DEFAULT);
float mSectionSelect = mSweepAngle / (sweepAngle / mSection);
for (int i = 0; i < mTexts.length; i++) {
if(i==(int)mSectionSelect){
mPaintText.setColor(selectedColor);
}else{
mPaintText.setColor(unSelectedColor);
}
mPaintText.getTextBounds(mTexts[i], 0, mTexts[i].length(), mRectText);
// 粗略把文字的寬度視為圓心角2*θ對應的弧長,利用弧長公式得到θ,下面用于修正角度
float θ = (float) (180 * mRectText.width() / 2 /
(Math.PI * (mRadius - mScaleShortLenth - mRectText.height())));
mPath.reset();
mPath.addArc(
mRectFInnerArc,
startAngle + i * (sweepAngle / mSection) - θ, // 正起始角度減去θ使文字居中對準長刻度
sweepAngle
);
canvas.drawTextOnPath(mTexts[i], mPath, 0, 0, mPaintText);
}
}
private void drawBlueArc(Canvas canvas) {
canvas.drawArc(mRectFArcChoose,startAngle,mSweepAngle,true,mPaintArcChoose);
canvas.save();
}
private void drawPoint(Canvas canvas) {
canvas.rotate(mSweepAngle, 0, 0);
canvas.drawBitmap(mBitmapPoint,-mRadiusChoose,-mBitmapPoint.getHeight()/2,null);
canvas.restore();
}
private void drawWhiteArc(Canvas canvas) {
canvas.drawArc(mRectFArcSmall,startAngle,sweepAngle,true,mPaintArcSmall);
}
private void drawCar(Canvas canvas) {
canvas.drawBitmap(mBitmapCar,-mBitmapCar.getWidth()/2,-mRadiusSmall/2-mBitmapCar.getHeight(),null);
}
private void drawValue(Canvas canvas) {
mPaintText.setTextSize(dpToPx(24));
mPaintText.setTextAlign(Paint.Align.CENTER);
mPaintText.setColor(Color.parseColor("#252c3d"));
mPaintText.setTypeface(Typeface.DEFAULT_BOLD);
int num = (int)(mSweepAngle / (sweepAngle / mSection));
if(!TextUtils.isEmpty(mTextsValue[num])){
canvas.drawText(mTextsValue[num],0, -dpToPx(12),mPaintText);
}else{
canvas.drawText(mTextsValue[num+1],0, -dpToPx(12),mPaintText);
}
}
private int dpToPx(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
private int spToPx(int sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());
}
/**
* 設置長刻度上的文字數組和對應顯示的值的數組,跟據數組個數來等分刻度
* @param texts
*/
public void setTextsArray(String[] texts,String[] textsValue){
if(texts==null||texts.length==0){
return;
}
this.mTexts = texts;
this.mTextsValue = textsValue;
this.mSection = texts.length - 1;
invalidate();
}
}
- 看代碼應該就看懂了,難點有一個,就是用到了逆矩陣,一開始我沒想到這個方法,計算的角度總是不對,后來發現這個方法好使。使用event.getRawX()獲取屏幕坐標,使用下面的方法轉換為畫布坐標后就輕松計算出了觸摸點到中心點的角度。
private void changeCanvasXY(Canvas canvas,float[] pts){
// 獲得當前矩陣的逆矩陣
Matrix invertMatrix = new Matrix();
canvas.getMatrix().invert(invertMatrix);
// 使用 mapPoints 將觸摸位置轉換為畫布坐標
invertMatrix.mapPoints(pts);
float x = Math.abs(pts[0]);
float y = Math.abs(pts[1]);
double z = Math.sqrt(x*x+y*y);
float round = (float)(Math.asin(y/z)/Math.PI*180);
LogUtils.e("觸摸的點:X==="+pts[0]+"Y==="+pts[1]+"===當前角度:"+round);
if(pts[0]<=0){
mSweepAngle = round;
}else{
mSweepAngle = sweepAngle - round;
}
}
大家可以根據自己的思路畫成一個整圓,也可以自己給這個view添加attr屬性進行設置,添加接口來獲取選擇的數據等,看大家的需要了。
參考鏈接:
http://www.gcssloop.com/customview/CustomViewIndex
https://github.com/woxingxiao/DashboardView