自定义View之炫酷的成绩展示界面

版权声明:本文为博主原创文章,未经博主允许不得转载。

前几天帮助我们移动组的一个小伙伴绘制界面,遇到了一个成绩展示界面,作为菜鸟的我顿时感觉天都塌陷下来了,就立马焉了,幸好我有我的绝招,当然是baidu,google了,终于皇天不负有心人,让我给找到了解决.的方法,自定义View来实现。先上UI妹子给的设计图,再看我写完之后的效果图。


效果图 2.png
效果图.gif

截屏工具不是太好,将就看看吧!!!
看到这里,我们就要实现它了,待我一步一步的去搞定它吧!!!

思路

首先,我们得有自己的思路啊,就像写作文一样,先要弄清楚自己的中心思想,然后在一步一步的去完成它。

1.自定义属性,如进度条的宽度、颜色,字体的大小、颜色等。
2.测量宽度和高度
3.画出我们心目中的效果图(当然不是用笔在笔记本上画了),我们采用Paint在Canvas上来绘制界面。
4.设置进度,相当于画龙点睛的作用了,使我们画出的静态页面动起来。

好了,下面我们将围绕我们的思路来一步一步的去实现它了。

1.自定义属性值

在value文件夹下面新建attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="circle_progress_view">
        <!--进度条的宽度-->
        <attr name="progress_paint_width" format="dimension"></attr>
        <!--进度条颜色-->
        <attr name="progress_paint_color" format="color"></attr>
        <!--字体颜色-->
        <attr name="progress_text_color_top" format="color"></attr>
        <!--字体大小-->
        <attr name="progress_text_size_top" format="dimension"></attr>
        <!--字体颜色-->
        <attr name="progress_text_color_bottom" format="color"></attr>
        <!--字体大小-->
        <attr name="progress_text_size_bottom" format="dimension"></attr>
    </declare-styleable>
</resources>

然后在自定义属性的地方我们去获取并且设置他们的默认值。

  /**
         * 获取自定的属性
         */
        TypedArray typedArray = getContext()
                .obtainStyledAttributes(attrs, R.styleable.circle_progress_view);
        mPaintWidth = typedArray
                .getDimension(R.styleable.circle_progress_view_progress_paint_width,
                        dip2px(context, 10));
        mTextSizeTop = typedArray
                .getDimension(R.styleable.circle_progress_view_progress_text_size_top,
                        dip2px(context, 18));
        mPaintColor = typedArray.getColor(R.styleable.circle_progress_view_progress_paint_color,
                mPaintColor);
        mTextColorTop = typedArray.getColor(R.styleable.circle_progress_view_progress_text_color_top,
                mTextColorTop);
        mTextSizeBottom = typedArray
                .getDimension(R.styleable.circle_progress_view_progress_text_size_bottom,
                        dip2px(context, 18));
        mTextColorBottom = typedArray
                .getColor(R.styleable.circle_progress_view_progress_text_color_bottom,
                        mTextColorTop);
        typedArray.recycle();//释放

        mPaintOut = new Paint();
        mPaintOut.setAntiAlias(true);
        mPaintOut.setColor(getResources().getColor(R.color.paint_out));
        mPaintOut.setStrokeWidth(mPaintWidth);
        /**
         * 画笔样式
         *
         */
        mPaintOut.setStyle(Paint.Style.STROKE);
        /**
         * 笔刷的样式
         * Paint.Cap.ROUND 圆形
         * Paint.Cap.SQUARE 方型
         */
        mPaintOut.setStrokeCap(Paint.Cap.ROUND);

        mPaintCurrent = new Paint();
        mPaintCurrent.setAntiAlias(true);
        mPaintCurrent.setColor(mPaintColor);
        mPaintCurrent.setStrokeWidth(mPaintWidth);
        mPaintCurrent.setStyle(Paint.Style.STROKE);
        mPaintCurrent.setStrokeCap(Paint.Cap.ROUND);

        mPaintTextTop = new Paint();
        mPaintTextTop.setAntiAlias(true);
        mPaintTextTop.setColor(mTextColorTop);
        mPaintTextTop.setStyle(Paint.Style.STROKE);
        mPaintTextTop.setTextSize(mTextSizeTop);

        mPaintTextBottom = new Paint();
        mPaintTextBottom.setAntiAlias(true);
        mPaintTextBottom.setColor(mTextColorBottom);
        mPaintTextBottom.setStyle(Paint.Style.STROKE);
        mPaintTextBottom.setTextSize(mTextSizeBottom);

2.测量

测量是在 onMeasure(int widthMeasureSpec, int heightMeasureSpec)方法里面来执行的
onMeasure()方法的作用就是测量View需要多大的空间,就是宽和高,本文中因为我们要绘制一个圆,所以我们需要一个正方形,那么我们就指定宽度和高度一致。

int width = MeasureSpec.getSize( widthMeasureSpec );
int height= MeasureSpec.getSize( heightMeasureSpec );
int size = width > height ? height : width;
setMeasuredDimension( size , size);

3.绘制出想要的效果图(背景弧和展示弧,展示字体)

(1)绘制操作是在onDraw(Canvas canvas)方法中来执行的。
(2)绘制弧我们用drawArc(RectF oval, float startAngle, floatsweepAngle,
boolean useCenter,Paint paint)方法

 oval :指定圆弧的外轮廓矩形区域。
 startAngle: 圆弧起始角度,单位为度。从180°为起始点
 sweepAngle: 圆弧扫过的角度,顺时针方向,单位为度。
 useCenter:  如果为True时,在绘制圆弧时将圆心包括在内,
             通常用来绘制扇形。如果false会将圆弧的两端用直线连接
 paint: 绘制圆弧的画板属性,如颜色,是否填充等
 public void drawArc(RectF oval, float startAngle, floatsweepAngle,
                                 boolean useCenter,Paint paint)

(3)我们先确定圆弧的外轮廓矩形区域的大小

RectF rectF = new RectF(mPaintWidth / 2,
                mPaintWidth / 2,
                getWidth() - mPaintWidth / 2,
                getHeight() - mPaintWidth / 2);

准备工作已经做完了,下面就让我们愉快的里绘制圆弧吧!!!

3.1背景弧

因为我们绘制的是一段弧线,故让它从135°开始,顺时针绘制到270°时停止,正好就是我们需要的那段弧线。

canvas.drawArc(rectF, 135, 270, false, mPaintOut);

3.2 当前进度弧

//获取当前的进度所对应的角度
 float currentAngle = mCurrent * sweepAngle / totalScore;
 canvas.drawArc(rectF, startAngle, currentAngle, false, mPaintCurrent);

3.3 两段文字

在绘制文字之前,我们需要搞清楚绘制文字的一些知识,先看看drawText(String text, float x, float y,Paint paint)方法吧

// 参数分别为 (文本 基线x 基线y 画笔)
canvas.drawText(String text,  float x, float y,Paint paint);

看到这里想必很多人都会问,基线是个神马东东,刚开始我也不太懂,直到我看了这位大神的一篇文章我才恍然大悟了http://blog.csdn.net/harvic880925/article/details/50423762不懂得小伙伴可以移步到这里去看看,搞清楚基线是个什么鬼之后就好办了。
首先,我们要把文字放到我们绘制的圆弧的中心位置,即确认基线的X和Y的坐标值。

X值:外轮廓矩形的宽度的一半减去文字宽度的一半。
Y值:外轮廓矩形的高度的一半减去文字高度的一半。
上代码:

        String text1 = mCurrent + "分";
        String text2 = "本次考试成绩";

        /**
         * 半径
         */
        float radius = (getWidth() - mPaintWidth) / 2;
        /**
         * 圆心和弦的距离
         */
        float dis = (float) Math.sqrt((radius * radius) / 2);

        /**
         * 绘制顶部文字
         */
        //测量文字的宽度
        float textWidth1 = mPaintTextTop.measureText(text1, 0, text1.length());
        //测量文字的高度
        float textHeight1 = (float) getTxtHeight(mPaintTextTop);
        float textHeight2 = (float) getTxtHeight(mPaintTextBottom);
        /**
         * 基线x的坐标即为:
         * view宽度的一半减去文字宽度的一半
         */
        float dx1 = getWidth() / 2 - textWidth1 / 2;
        /**
         * 基线y的坐标为:
         * view高度的一半减去文字高度的一半
         */
        float dy1 = getHeight() / 2 - textHeight1 / 2 + dis - textHeight2;
        /**
         * 绘制底部文字
         */
        float textWidth2 = mPaintTextBottom.measureText(text2, 0, text2.length());
        float dx2 = getWidth() / 2 - textWidth2 / 2;
        float dy2 = getHeight() / 2 - textHeight2 / 2 + dis;

        canvas.drawText(text1, dx1, dy1, mPaintTextTop);
        canvas.drawText(text2, dx2, dy2, mPaintTextBottom);

这样我们才是把文字给放到圆弧的中心位置,可是效果图上面的底部文字是在弦上的,所以我们还的计算圆心到弦的距离(这里就要运用初中数学知识了,赶紧恶补知识吧!)
(1)确定圆的半径,由以上可知,半径为外轮廓矩形的宽度的一半(我们是在一个正方形中来绘制圆弧的)。

       /**
         * 半径
         */
        float radius = (getWidth() - mPaintWidth) / 2;

效果图为:
(2)由于我们切掉的弧的角度为90°,则可以根据勾股定理来计算出圆心和弦的距离,这样我们就可以规定文字的位置了。

文字一的位置:半径加上计算出的距离减去文字二的高度在减去文字一高度的一半。
文字二的位置:半径加上计算出的距离减去文字二高度的一半。

       /**
         * 圆心和弦的距离
         */
        float dis = (float) Math.sqrt((radius * radius) / 2);

如上,我们就让文字按照我们计算好的位置显示了。

        float dy1 = getHeight() / 2 - textHeight1 / 2 + dis - textHeight2;
        float dy2 = getHeight() / 2 - textHeight2 / 2 + dis;

4.添加动画效果

       /**
         * 进度条从0到指定数字的动画
         * 除了startAnimator1()方法中用的ValueAnimator.ofInt(),我们还有
         * ofFloat()、ofObject()这些生成器的方法;
         * 我们可以通过ofObject()去实现自定义的数值生成器
         */
        ValueAnimator animator = ValueAnimator.ofFloat(0, currentScore);
        animator.setDuration(speed);
        /**
         *  Interpolators  插值器,用来控制具体数值的变化规律
         *  LinearInterpolator  线性
         */
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                /**
                 * 通过这样一个监听事件,我们就可以获取
                 * 到ValueAnimator每一步所产生的值。
                 *
                 * 通过调用getAnimatedValue()获取到每个时间因子所产生的Value。
                 * */
                float current = (float) valueAnimator.getAnimatedValue();
                view.setmCurrent((int) current);
            }
        });
        animator.start();

到这里,所有的绘制工作已经完成,来欣赏一下我们的劳动成果吧,哈哈哈。
activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    tools:context="com.gifts.circleprogressproject.MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="总成绩:" />

            <EditText
                android:id="@+id/ed_total_score"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:maxLength="3" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="当前成绩:" />

            <EditText
                android:id="@+id/ed_current_score"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:maxLength="3" />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:gravity="center"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center|left"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="转动速度:" />

            <Spinner
                android:id="@+id/sp_speed"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

        <Button
            android:id="@+id/btn_submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="确定" />


    </LinearLayout>


    <com.gifts.circleprogressproject.ProgressView
        android:id="@+id/circleProgress"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        app:progress_paint_width="30dp"
        app:progress_text_color_bottom="#000000"
        app:progress_text_color_top="@color/paint_current"
        app:progress_text_size_bottom="20dp"
        app:progress_text_size_top="40dp"></com.gifts.circleprogressproject.ProgressView>

</LinearLayout>

MainActivity.java

package com.gifts.circleprogressproject;

import android.animation.ValueAnimator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private EditText edTotalScore;
    private EditText edCurrentScore;
    private Spinner spSpeed;
    private Button btnSubmit;
    private ProgressView view;
    /**
     * 总成绩
     */
    private int totalScore = 100;
    /**
     * 当前成绩
     */
    private int currentScore = 98;
    /**
     * 转动的速度
     */
    private long speed = 2000;

    private List<String> listSpeeds;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        view = findViewById(R.id.circleProgress);
        findViews();
        initData();

        initView();
        initEvent();

    }

    private void initData() {
        listSpeeds = new ArrayList<>();
        listSpeeds.add("1000");
        listSpeeds.add("2000");
        listSpeeds.add("3000");
        listSpeeds.add("4000");
        listSpeeds.add("5000");
        adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1, listSpeeds);
        spSpeed.setAdapter(adapter);
    }

    /**
     * 完成后的回调接口
     */
    private void initEvent() {
        view.setOnLoadingCompleteListenter(new ProgressView.OnLoadingCompleteListenter() {
            @Override
            public void onComplete() {
                Toast.makeText(MainActivity.this, "完成", Toast.LENGTH_SHORT).show();
            }
        });
        spSpeed.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                speed = Long.parseLong(listSpeeds.get(i));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String data1 = edTotalScore.getText().toString().trim();
                String data2 = edCurrentScore.getText().toString().trim();
                if (TextUtils.isEmpty(data1)) {
                    Toast.makeText(MainActivity.this, "填写总成绩", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(data2)) {
                    Toast.makeText(MainActivity.this, "填写当前成绩", Toast.LENGTH_SHORT).show();
                    return;
                }
                totalScore = Integer.parseInt(data1);
                currentScore = Integer.parseInt(data2);
                if (currentScore > totalScore) {
                    Toast.makeText(MainActivity.this, "当前成绩不能大于总成绩", Toast.LENGTH_SHORT).show();
                    return;

                }
                initView();
            }
        });

    }

    private void initView() {
        view.setTotalScore(totalScore);
        /**
         * 进度条从0到指定数字的动画
         * 除了startAnimator1()方法中用的ValueAnimator.ofInt(),我们还有
         * ofFloat()、ofObject()这些生成器的方法;
         * 我们可以通过ofObject()去实现自定义的数值生成器
         */
        ValueAnimator animator = ValueAnimator.ofFloat(0, currentScore);
        animator.setDuration(speed);
        /**
         *  Interpolators  插值器,用来控制具体数值的变化规律
         *  LinearInterpolator  线性
         */
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                /**
                 * 通过这样一个监听事件,我们就可以获取
                 * 到ValueAnimator每一步所产生的值。
                 *
                 * 通过调用getAnimatedValue()获取到每个时间因子所产生的Value。
                 * */
                float current = (float) valueAnimator.getAnimatedValue();
                view.setmCurrent((int) current);
            }
        });
        animator.start();

    }


    /**
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2017-11-03 16:55:55 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void findViews() {
        edTotalScore = (EditText) findViewById(R.id.ed_total_score);
        edCurrentScore = (EditText) findViewById(R.id.ed_current_score);
        spSpeed = (Spinner) findViewById(R.id.sp_speed);
        btnSubmit = (Button) findViewById(R.id.btn_submit);


    }


}

ProgressView .java

package com.gifts.circleprogressproject;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.icu.util.Measure;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * 包名: com.gifts.circleprogressproject
 * 创建人: Liu_xg
 * 时间: 2017/11/3 11:39
 * 描述: 自定义view
 * 修改人:
 * 修改时间:
 * 修改备注:
 */
public class ProgressView extends View {
    /**
     * 背景的圆
     */
    private Paint mPaintOut;
    /**
     * 当前的圆
     */
    private Paint mPaintCurrent;
    /**
     * 字体
     */
    private Paint mPaintTextTop;
    private Paint mPaintTextBottom;

    /**
     * 自定义属性
     */
    private float mTextSizeTop;
    private float mPaintWidth;
    private int mPaintColor = getResources().getColor(R.color.paint_current);
    private int mTextColorTop = Color.BLACK;
    private int mTextColorBottom = Color.BLACK;
    private float mTextSizeBottom;
    /**
     * 开始的角度
     * 直角坐标系
     * 左边  180
     * 上面  270
     * 右边  0
     * 下边  90
     */
    private int startAngle = 135;
    /**
     * 要画的圆弧的度数
     * 圆 :360
     */
    private int sweepAngle = 270;
    /**
     * 总成绩
     */
    private int totalScore = 100;
    /**
     * 当前成绩
     */
    private int mCurrent;


    private OnLoadingCompleteListenter onLoadingCompleteListenter;

    public ProgressView(Context context) {
        this(context, null);
    }

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

    public ProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        /**
         * 获取自定的属性
         */
        TypedArray typedArray = getContext()
                .obtainStyledAttributes(attrs, R.styleable.circle_progress_view);
        mPaintWidth = typedArray
                .getDimension(R.styleable.circle_progress_view_progress_paint_width,
                        dip2px(context, 10));
        mTextSizeTop = typedArray
                .getDimension(R.styleable.circle_progress_view_progress_text_size_top,
                        dip2px(context, 18));
        mPaintColor = typedArray.getColor(R.styleable.circle_progress_view_progress_paint_color,
                mPaintColor);
        mTextColorTop = typedArray.getColor(R.styleable.circle_progress_view_progress_text_color_top,
                mTextColorTop);
        mTextSizeBottom = typedArray
                .getDimension(R.styleable.circle_progress_view_progress_text_size_bottom,
                        dip2px(context, 18));
        mTextColorBottom = typedArray
                .getColor(R.styleable.circle_progress_view_progress_text_color_bottom,
                        mTextColorTop);
        typedArray.recycle();//释放

        mPaintOut = new Paint();
        mPaintOut.setAntiAlias(true);
        mPaintOut.setColor(getResources().getColor(R.color.paint_out));
        mPaintOut.setStrokeWidth(mPaintWidth);
        /**
         * 画笔样式
         *
         */
        mPaintOut.setStyle(Paint.Style.STROKE);
        /**
         * 笔刷的样式
         * Paint.Cap.ROUND 圆形
         * Paint.Cap.SQUARE 方型
         */
        mPaintOut.setStrokeCap(Paint.Cap.ROUND);

        mPaintCurrent = new Paint();
        mPaintCurrent.setAntiAlias(true);
        mPaintCurrent.setColor(mPaintColor);
        mPaintCurrent.setStrokeWidth(mPaintWidth);
        mPaintCurrent.setStyle(Paint.Style.STROKE);
        mPaintCurrent.setStrokeCap(Paint.Cap.ROUND);

        mPaintTextTop = new Paint();
        mPaintTextTop.setAntiAlias(true);
        mPaintTextTop.setColor(mTextColorTop);
        mPaintTextTop.setStyle(Paint.Style.STROKE);
        mPaintTextTop.setTextSize(mTextSizeTop);

        mPaintTextBottom = new Paint();
        mPaintTextBottom.setAntiAlias(true);
        mPaintTextBottom.setColor(mTextColorBottom);
        mPaintTextBottom.setStyle(Paint.Style.STROKE);
        mPaintTextBottom.setTextSize(mTextSizeBottom);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //宽度
        int width = MeasureSpec.getSize(widthMeasureSpec);
        //高度
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int size = width > height ? height : width;
        setMeasuredDimension(size, size);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        /**
         * mPaintWidth  圆弧的宽度
         *
         * RectF就相当于一个画布,画布有上下左右四个顶点,
         * 宽度为 right - left
         * 高度为 bottom - top
         *
         */
        RectF rectF = new RectF(mPaintWidth / 2,
                mPaintWidth / 2,
                getWidth() - mPaintWidth / 2,
                getHeight() - mPaintWidth / 2);

        canvas.drawArc(rectF, startAngle, sweepAngle, false, mPaintOut);

        float currentAngle = mCurrent * sweepAngle / totalScore;
        canvas.drawArc(rectF, startAngle, currentAngle, false, mPaintCurrent);

        String text1 = mCurrent + "分";
        String text2 = "本次考试成绩";

        /**
         * 半径
         */
        float radius = (getWidth() - mPaintWidth) / 2;
        /**
         * 圆心和弦的距离
         */
        float dis = (float) Math.sqrt((radius * radius) / 2);

        /**
         * 绘制顶部文字
         */
        //测量文字的宽度
        float textWidth1 = mPaintTextTop.measureText(text1, 0, text1.length());
        //测量文字的高度
        float textHeight1 = (float) getTxtHeight(mPaintTextTop);
        float textHeight2 = (float) getTxtHeight(mPaintTextBottom);
        /**
         * 基线x的坐标即为:
         * view宽度的一半减去文字宽度的一半
         */
        float dx1 = getWidth() / 2 - textWidth1 / 2;
        /**
         * 基线y的坐标为:
         * view高度的一半减去文字高度的一半
         */
        float dy1 = getHeight() / 2 - textHeight1 / 2 + dis - textHeight2;
        /**
         * 绘制底部文字
         */
        float textWidth2 = mPaintTextBottom.measureText(text2, 0, text2.length());
        float dx2 = getWidth() / 2 - textWidth2 / 2;
        float dy2 = getHeight() / 2 - textHeight2 / 2 + dis;

        canvas.drawText(text1, dx1, dy1, mPaintTextTop);
        canvas.drawText(text2, dx2, dy2, mPaintTextBottom);


        /**
         * 完成
         */
        if (getOnLoadingCompleteListenter() != null && mCurrent == totalScore) {
            getOnLoadingCompleteListenter().onComplete();
        }

    }


    public int getmCurrent() {
        return mCurrent;
    }

    /**
     * 设置当前进度并且重新绘制界面
     *
     * @param mCurrent
     */
    public void setmCurrent(int mCurrent) {
        this.mCurrent = mCurrent;
        //重新绘制的方法
        invalidate();
    }

    public int getStartAngle() {
        return startAngle;
    }

    public void setStartAngle(int startAngle) {
        this.startAngle = startAngle;
    }

    public int getSweepAngle() {
        return sweepAngle;
    }

    public void setSweepAngle(int sweepAngle) {
        this.sweepAngle = sweepAngle;
    }

    public int getTotalScore() {
        return totalScore;
    }

    public void setTotalScore(int totalScore) {
        this.totalScore = totalScore;
    }

    /**
     * 获取文字的高度
     *
     * @param mPaint
     * @return
     */
    public double getTxtHeight(Paint mPaint) {
        Paint.FontMetrics fm = mPaint.getFontMetrics();
        return Math.ceil(fm.descent - fm.ascent);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    interface OnLoadingCompleteListenter {
        void onComplete();
    }

    public OnLoadingCompleteListenter getOnLoadingCompleteListenter() {
        return onLoadingCompleteListenter;
    }

    public void setOnLoadingCompleteListenter(OnLoadingCompleteListenter onLoadingCompleteListenter) {
        this.onLoadingCompleteListenter = onLoadingCompleteListenter;
    }
}

GitHub传送门:https://github.com/liuxinggen/CircleProgressProject

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容