天天看點

安卓運動圓環自定義View

運動圓環自定義View.gif

記得這個東西原來有個同僚問過我,當時正在自學自定義View和屬性動畫這一塊,對這個功能也沒有寫過,是以就google了一下,發了幾個類似效果的github項目給朋友,今天禮拜天難得有心情寫寫代碼,是以想想實作一下這個自定義View的效果。

首先,我們從這個gif的效果圖中就可以得知這個自定義View我們需要哪些自定義屬性,内部圓環的顔色、外部圓環的顔色、圓環的寬度、字型的大小、顔色,話不多說,直接撸碼。

<!-- 運動圓環自定義屬性 -->
    <declare-styleable name="MotionCrcle">
        <attr name="outerCrcleColor" format="color"></attr>
        <attr name="innerCrcleColor" format="color"></attr>
        <attr name="crcleTextColor" format="color"></attr>
        <attr name="crcleTextSize" format="integer"></attr>
        <attr name="crcleWidth" format="integer"></attr>
    </declare-styleable>
           
/**
 * Created by Administrator on 2018/5/13.
 * 運動圓環自定義View
 */

public class MotionCrcle extends View {
    /**
     * 外部圓環顔色
     */
    private int mOuterColor = Color.BLUE;
    /**
     * 裡面圓環顔色
     */
    private int mInnerColor = Color.RED;
    /**
     * 跑步數的文字大小
     */
    private int mTextSize = 30;
    /**
     * 跑步文字的顔色
     */
    private int mTextColor = Color.BLACK;
    /**
     * 圓環的寬度
     */
    private int mCrcleWidth = 45;
    private Paint mOuterPaint, mInnerPaint, mTextPaint;
    private float mMaxSteps = 0;
    private int mCurrentSteps = 0;
    public MotionCrcle(Context context) {
        this(context, null);
    }

    public MotionCrcle(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MotionCrcle(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MotionCrcle);
        mOuterColor = array.getColor(R.styleable.MotionCrcle_outerCrcleColor, mOuterColor);
        mInnerColor = array.getColor(R.styleable.MotionCrcle_innerCrcleColor, mInnerColor);
        mCrcleWidth = array.getInt(R.styleable.MotionCrcle_crcleWidth, mCrcleWidth);
        mTextColor = array.getColor(R.styleable.MotionCrcle_crcleTextColor, mTextColor);
        mTextSize = array.getInt(R.styleable.MotionCrcle_crcleTextSize, mTextSize);
        initPaint();
        array.recycle();
    }

    public synchronized void setmMaxSteps(float mMaxSteps) {
        this.mMaxSteps = mMaxSteps;
    }

    public synchronized void setmCurrentSteps(int mCurrentSteps) {
        this.mCurrentSteps = mCurrentSteps;
        invalidate();
    }

    private void initPaint() {
        mOuterPaint = new Paint();
        mOuterPaint.setAntiAlias(true);
        mOuterPaint.setStrokeWidth(mCrcleWidth);
        mOuterPaint.setStrokeCap(Paint.Cap.ROUND);
        mOuterPaint.setStyle(Paint.Style.STROKE);
        mOuterPaint.setColor(mOuterColor);

        mInnerPaint = new Paint();
        mInnerPaint.setAntiAlias(true);
        mInnerPaint.setStrokeWidth(mCrcleWidth);
        mInnerPaint.setStrokeCap(Paint.Cap.ROUND);
        mInnerPaint.setStyle(Paint.Style.STROKE);
        mInnerPaint.setColor(mInnerColor);

        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(mTextSize);
        mTextPaint.setColor(mTextColor);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if(width != height){
            /**
             * 因為運動圓環是一個正方形,是以我們要設定一個最小值作為View的長度
             */
            int min = Math.min(width, height);
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, MeasureSpec.EXACTLY);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(min, MeasureSpec.EXACTLY);
            setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
       //因為圓環本身是具有寬度的,是以我們這裡左邊的頂點要往右mCrcleWidth個距離,右邊底部的點要往左,是以要減去mCrcleWidth
        RectF recf = new RectF(mCrcleWidth, mCrcleWidth,
                getWidth() - mCrcleWidth, getHeight() - mCrcleWidth);
      //135是外部圓環的初始角度,270是所畫的總角度數
        canvas.drawArc(recf, 135, 270, false, mOuterPaint);
        if(mCurrentSteps == 0){
            return;
        }
      //算出目前步數是最大步數的比值
        float angle = mCurrentSteps / mMaxSteps;
        canvas.drawArc(recf, 135, 270 * angle, false, mInnerPaint);
        String stepText = mCurrentSteps+"";
        Rect bounds = new Rect();
      //算出步數文字的baseLine,也就是基準線
        mTextPaint.getTextBounds(stepText, 0, stepText.length(), bounds);
        int x = getWidth() / 2 - bounds.width() / 2;
        Paint.FontMetricsInt metrices = mTextPaint.getFontMetricsInt();
        int diffY = (metrices.bottom - metrices.top) / 2 - metrices.bottom;
        int baseLine = getHeight() / 2 + diffY;
        canvas.drawText(stepText, x, baseLine, mTextPaint);
    }

}
           

文字基準線說明圖.jpg

文字的繪制和畫圓畫弧不一樣,其實仔細想想也明白,如果繪制按照左上角開始的話是不現實的,因為文字不可能是簡單的頂部或底部對其,應該是重心對齊,簡單說就是基準線,是以代碼中基準線的算法是bottom-top再除以2減去bottom,以基準線開始繪制,top就是負數,bottom是正數。

public class MainActivity extends AppCompatActivity {

    private Button mBtn;
    private baohuo.rzj.com.myapplication.Views.MotionCrcle mCrcle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtn = (Button) findViewById(R.id.btn);
        mCrcle = (MotionCrcle) findViewById(R.id.motion_crcle);
        mCrcle.setmMaxSteps(10000);
        final ValueAnimator animator = ObjectAnimator.ofFloat(0,4500);
        animator.setDuration(2000);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float value = (float) valueAnimator.getAnimatedValue();
                mCrcle.setmCurrentSteps((int) value);
            }
        });
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animator.start();
            }
        });
    }
}
           

以上是Activity的代碼,非常簡單,不做解釋,這個值得一提的是,我在寫的時候内部圓環一直沒有繪制,文字在不斷變化,通過debug發現,我把步數最大值和目前步數設定為int,一個小的int除以大的int的到的隻有0,是以我把最大步數改為float,這樣得出的值就有小數位,最後附上xml代碼。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="baohuo.rzj.com.myapplication.MainActivity">
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:text="運動圓環開啟"
        android:gravity="center"/>
    <baohuo.rzj.com.myapplication.Views.MotionCrcle
        android:id="@+id/motion_crcle"
        android:layout_below="@+id/btn"
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:outerCrcleColor="@color/colorPrimary"
        app:innerCrcleColor="@color/colorAccent"
        app:crcleTextColor="@color/colorPrimaryDark"
        app:crcleTextSize="40"
        app:crcleWidth="20"/>


</RelativeLayout>
           

繼續閱讀