带有百分比数字的横向渐变颜色进度条

本文代码是经过简书另一个哥们控件修改而来(只改了小部分),链接
效果如下

TIM图片20171129174213.png

相对之前别人的代码修改了两点:
1、增加了百分比背景
2、优化了百分比展示超出界面问题
因为是为了特定需求而做的,所以都写的比较死,但注释够详细,有需要的直接拿去修改相应代码就行
上代码:
先定义style:

    
    <declare-styleable name="ProgressWithNum">
        <attr name="textSize" format="dimension"/>
        <attr name="textColor" format="color"/>
        <attr name="textVisible" format="enum">
            <enum name="visible" value="0"/>
            <enum name="inVisible" value="1"/>
        </attr>
        <attr name="lineHeight" format="dimension"/>
        <attr name="lineStartColor" format="color"/>
        <attr name="lineEndColor" format="color"/>
        <!--另一个背景进度条渐变结束颜色-->
        <attr name="bgLineColor" format="color"/>

    </declare-styleable>

接着控件代码:

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ProgressBar;
import com.ashokvarma.bottomnavigation.utils.Utils;
import com.tianwen.blindlibrary.R;

/**
 * Created by pkxutao on 2017/11/9.
 */

public class ProgressWithNum extends ProgressBar {

    //各种控件属性的默认值

    //字体大小
    private static final int DEFAULT_TEXT_SIZE = 15;

    //字体颜色
    private static final int DEFAULT_TEXT_COLOR = 0XFFFC00D1;

    //进度条宽度
    private static final int DEFAULT_LINE_HEIGHT = 10;

    //进度条渐变前颜色
    private static final int DEFAULT_LINE_START_COLOR = 0XFF95dee1;

    //进度条渐变后的颜色
    private static final int DEFAULT_LINE_END_COLOR = 0XFF1AA0E5;

    //背景进度条颜色
    private static final int DEFAULT_BG_LINE_COLOR = 0xFFd3d6da;

    //字体是否显示
    protected static final int DEFAULT_TEXT_VISIBLE = 0;
    //默认值的赋值

    protected int textSize = DEFAULT_TEXT_SIZE;

    protected int textColor = DEFAULT_TEXT_COLOR;

    protected int lineHeight = DEFAULT_LINE_HEIGHT;

    protected int lineStartColor = DEFAULT_LINE_START_COLOR;

    protected int lineEndColor = DEFAULT_LINE_END_COLOR;

    protected int bgLineColor = DEFAULT_BG_LINE_COLOR;

    protected int textVisible = DEFAULT_TEXT_VISIBLE;

    protected boolean mTextVisible = true;

    private Paint mPaint = new Paint();

    private int progressBarWidth = 0;
    private Context mContext;

    //构造方法
    public ProgressWithNum(Context context, AttributeSet attrs) {

        this(context, attrs, 0);

    }

    public ProgressWithNum(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        setHorizontalScrollBarEnabled(true);
        //设置进度条自定义的属性
        obtainStyledAttributes(attrs);
        mPaint.setTextSize(textSize);
        mPaint.setColor(textColor);
    }

    private void obtainStyledAttributes(AttributeSet attrs) {
        //找到资源styleable文件
        final TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.ProgressWithNum);
        //各种属性的赋值
        textSize = (int) attributes.getDimension(R.styleable.ProgressWithNum_textSize, DEFAULT_TEXT_SIZE);
        textColor = attributes.getColor(R.styleable.ProgressWithNum_textColor, DEFAULT_TEXT_COLOR);
//        textVisible = attributes.getInt(R.styleable.ProgressWithNum_textVisiable, DEFAULT_TEXT_VISIBLE);
        if (textVisible == 1) {
            mTextVisible = false;
        }
        lineHeight = (int) attributes.getDimension(R.styleable.ProgressWithNum_lineHeight, DEFAULT_LINE_HEIGHT);
        lineStartColor = attributes.getColor(R.styleable.ProgressWithNum_lineStartColor, DEFAULT_LINE_START_COLOR);
        lineEndColor = attributes.getColor(R.styleable.ProgressWithNum_lineEndColor, DEFAULT_LINE_END_COLOR);
        bgLineColor = attributes.getColor(R.styleable.ProgressWithNum_bgLineColor, DEFAULT_BG_LINE_COLOR);
        attributes.recycle();

    }


    @Override

    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthModule = MeasureSpec.getMode(widthMeasureSpec);
        int heightModule = MeasureSpec.getMode(heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (widthModule != MeasureSpec.EXACTLY) {
            width = width + getPaddingLeft() + getPaddingBottom();

        }

        if (heightModule != MeasureSpec.EXACTLY) {
            float textHeight = mPaint.ascent() + mPaint.descent();
            int result = getPaddingBottom() + getPaddingTop() + (int) Math.max(lineHeight, textHeight);
            if (heightModule == MeasureSpec.AT_MOST) {
                height = Math.min(height, result);
            }

        }
        progressBarWidth = width - getPaddingLeft() - getPaddingRight();

        //把修改后的宽高上传
        setMeasuredDimension(width, height);

    }


    @Override

    protected synchronized void onDraw(Canvas canvas) {

        canvas.save();

        canvas.translate(getPaddingLeft(), getHeight() / 2);

        float percent = getProgress() * 1.0f / getMax();

        String percentText = (int)(percent * 100) + "%";

        float textWidth = mPaint.measureText(percentText);

        float textHeight = (mPaint.descent() + mPaint.ascent()) / 2;

        float progressLeftWith = percent * progressBarWidth ;

        boolean rightShow = true;

        if (progressLeftWith + textWidth / 2 >= progressBarWidth) {

            progressLeftWith = progressBarWidth - textWidth;

            rightShow = false;

        }

        //绘画渐变进度条

        float endX = progressLeftWith;

        if (endX > 0) {

            int[] mColors = {lineStartColor, lineEndColor};

            //渐变颜色

            Shader oShader = mPaint.getShader();

            LinearGradient shader = new LinearGradient(0, 0, endX, 0, mColors, null,

                    Shader.TileMode.CLAMP);

            mPaint.setShader(shader);

            //渐变结束

            //线的圆角

            mPaint.setStrokeCap(Paint.Cap.ROUND);

            //线的高度

            mPaint.setStrokeWidth(lineHeight);

            //绘画线

            canvas.drawLine(0, 0, endX, 0, mPaint);


            mPaint.setShader(oShader);

        }

        //绘画背景进度条
        if (rightShow) {

            float start = progressLeftWith + textWidth;

            mPaint.setColor(bgLineColor);

            mPaint.setStrokeWidth(lineHeight);

            canvas.drawLine(start, 0, progressBarWidth, 0, mPaint);

        }





        if (progressLeftWith+textWidth+Utils.dp2px(mContext, 8) > progressBarWidth && mTextVisible){
            //字体宽度超出progressbar整体宽度,就直接画在最后,否则会不显示字体

            //画百分比背景
            Drawable drawable = mContext.getResources().getDrawable(R.drawable.shape_progress_text_bg_blue_round_stroke);
            drawable.setBounds(progressBarWidth-(int)(textWidth+Utils.dp2px(mContext, 8)), (int)textHeight- Utils.dp2px(mContext, 3),
                    progressBarWidth,
                    -(int)textHeight+Utils.dp2px(mContext, 3));
            drawable.draw(canvas);
            //绘画显示百分比
            mPaint.setColor(textColor);
            mPaint.setAntiAlias(true);
            canvas.drawText(percentText, progressBarWidth-textWidth-Utils.dp2px(mContext, 4), -textHeight, mPaint);
        }else if(mTextVisible){
            //画百分比背景
            Drawable drawable = mContext.getResources().getDrawable(R.drawable.shape_progress_text_bg_blue_round_stroke);
            drawable.setBounds((int)progressLeftWith, (int)textHeight- Utils.dp2px(mContext, 3),
                    (int)(progressLeftWith+textWidth)+Utils.dp2px(mContext, 8),
                    -(int)textHeight+Utils.dp2px(mContext, 3));
            drawable.draw(canvas);
            //绘画显示百分比
            mPaint.setColor(textColor);
            mPaint.setAntiAlias(true);
            canvas.drawText(percentText, progressLeftWith+Utils.dp2px(mContext, 4), -textHeight, mPaint);
        }
        canvas.restore();

    }
}

布局代码:

            <com.tianwen.blindlibrary.views.ProgressWithNum"
                android:layout_width="0dp"
                android:layout_height="22dp"
                android:layout_marginEnd="15dp"
                android:layout_marginStart="15dp"
                android:layout_marginTop="8dp"
                app:lineStartColor="#57c6fe"
                app:lineEndColor="#508eef"
                app:textSize="10sp"
                app:textColor="#508eef"
                android:progress="50"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView20"
                app:layout_goneMarginRight="15dp"
                app:progress_reached_bar_height="2dp"
                app:progress_unreached_bar_height="2dp" />

使用方法和普通progressbar一样

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

推荐阅读更多精彩内容