[Android][自定義進度條]③--繪制條形進度條

增加代碼

 @Override
    protected synchronized void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(getPaddingLeft(),getHeight()/2);

        boolean noNeedUnreach=false;

        //draw reach bar
        String text=getProgress()+"%";
        int textWidth= (int) mPaint.measureText(text);

        float radio=getProgress()*1.0f/getMax();
        float progressX=radio*mRealWidth;
        if(progressX+textWidth>mRealWidth)
        {
            progressX=mRealWidth-textWidth;
            noNeedUnreach=true;
        }

        float endX=progressX-mTextOffset/2;
        if(endX>0)
        {
            mPaint.setColor(mReachColor);
            mPaint.setStrokeWidth(mReachHeight);
            canvas.drawLine(0,0,endX,0,mPaint);
        }

        //draw text
        mPaint.setColor(mTextColor);
        int y= (int) (-(mPaint.descent()+mPaint.ascent())/2);
        canvas.drawText(text,progressX,y,mPaint);

        //draw unreach bar
        if(!noNeedUnreach)
        {
            float start=progressX+mTextOffset/2+textWidth;
            mPaint.setColor(mUnReachColor);
            mPaint.setStrokeWidth(mUnReachHeight);
            canvas.drawLine(start,0,mRealWidth,0,mPaint);

        }
        canvas.restore();
    }

完整代碼

package myapplication4.xt.com.myapplication4;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ProgressBar;

/**
 * Created by TONG on 2017/3/23.
 */

public class HorizontalProgressbarWithProgress extends ProgressBar{

    private static final int DEFAULT_TEXT_SIZE=10;//sp
    private static final int DEFAULT_TEXT_COLOR=0xFFFC00D1;
    private static final int DEFAULT_COLOR_UNREACH=0xFFD3D6DA;
    private static final int DEFAULT_HEIGHT_UNREACH=2;
    private static final int DEFAULT_COLOR_REACH=DEFAULT_TEXT_COLOR;
    private static final int DEFAULT_HEIGHT_REACH=2;//dp
    private static final int DEFAULT_TEXT_OFFSET=10;//dp

    protected int mTextSize=sp2px(DEFAULT_TEXT_SIZE);
    protected int mTextColor=DEFAULT_TEXT_COLOR;
    protected int mUnReachColor=DEFAULT_COLOR_UNREACH;
    protected int mUnReachHeight=dp2px(DEFAULT_HEIGHT_UNREACH);
    protected int mReachColor=DEFAULT_COLOR_REACH;
    protected int mReachHeight=dp2px(DEFAULT_HEIGHT_REACH);
    protected int mTextOffset=dp2px(DEFAULT_TEXT_OFFSET);

    protected Paint mPaint=new Paint();

    protected int mRealWidth;

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

    public HorizontalProgressbarWithProgress(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public HorizontalProgressbarWithProgress(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        obtainStyledAttrs(attrs);

    }

    /**
     * 獲取自定義屬性
     * @param attrs
     */
    private void obtainStyledAttrs(AttributeSet attrs) {
        TypedArray ta=getContext().obtainStyledAttributes
                (attrs,R.styleable.HorizontalProgressbarWithProgress);

        mTextSize= (int) ta.getDimension
                (R.styleable.HorizontalProgressbarWithProgress_progress_text_size,mTextSize);

        mTextColor=ta.getColor
                (R.styleable.HorizontalProgressbarWithProgress_progress_text_color,mTextColor);

        mTextOffset= (int) ta.getDimension
                (R.styleable.HorizontalProgressbarWithProgress_progress_text_offset,mTextOffset);

        mUnReachColor=ta.getColor
                (R.styleable.HorizontalProgressbarWithProgress_progress_unreach_color,mUnReachColor);

        mUnReachHeight= (int) ta.getDimension
                (R.styleable.HorizontalProgressbarWithProgress_progress_unreach_height,mUnReachHeight);

        mReachColor=ta.getColor
                (R.styleable.HorizontalProgressbarWithProgress_progress_reach_color,mReachColor);

        mReachHeight= (int) ta.getDimension
                (R.styleable.HorizontalProgressbarWithProgress_progress_reach_height,mReachHeight);

        ta.recycle();

        mPaint.setTextSize(mTextSize);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthVal=MeasureSpec.getSize(widthMeasureSpec);
        int height=measureHeight(heightMeasureSpec);
        setMeasuredDimension(widthVal,height);

        mRealWidth=getMeasuredWidth()-getPaddingLeft()-getPaddingRight();
    }

    private int measureHeight(int heightMeasureSpec) {
        int result;
        int mode= MeasureSpec.getMode(heightMeasureSpec);
        int size=MeasureSpec.getSize(heightMeasureSpec);

        if(mode==MeasureSpec.EXACTLY)
        {
            result= size;
        }else {
            int textHeight= (int) (mPaint.descent()-mPaint.ascent());
            result=getPaddingTop()+getPaddingBottom()
                    +Math.max(Math.max(mReachHeight,mUnReachHeight),
                    Math.abs(textHeight));
            if(mode==MeasureSpec.AT_MOST)
            {
                result=Math.min(result,size);
            }
        }
        return result;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(getPaddingLeft(),getHeight()/2);

        boolean noNeedUnreach=false;

        //draw reach bar
        String text=getProgress()+"%";
        int textWidth= (int) mPaint.measureText(text);

        float radio=getProgress()*1.0f/getMax();
        float progressX=radio*mRealWidth;
        if(progressX+textWidth>mRealWidth)
        {
            progressX=mRealWidth-textWidth;
            noNeedUnreach=true;
        }

        float endX=progressX-mTextOffset/2;
        if(endX>0)
        {
            mPaint.setColor(mReachColor);
            mPaint.setStrokeWidth(mReachHeight);
            canvas.drawLine(0,0,endX,0,mPaint);
        }

        //draw text
        mPaint.setColor(mTextColor);
        int y= (int) (-(mPaint.descent()+mPaint.ascent())/2);
        canvas.drawText(text,progressX,y,mPaint);

        //draw unreach bar
        if(!noNeedUnreach)
        {
            float start=progressX+mTextOffset/2+textWidth;
            mPaint.setColor(mUnReachColor);
            mPaint.setStrokeWidth(mUnReachHeight);
            canvas.drawLine(start,0,mRealWidth,0,mPaint);

        }
        canvas.restore();
    }

    protected int dp2px(int dpval){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dpval,
                getResources().getDisplayMetrics());
    }

    protected int sp2px(int spValue){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,spValue,
                getResources().getDisplayMetrics());
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:hyman="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <myapplication4.xt.com.myapplication4.HorizontalProgressbarWithProgress
            android:id="@+id/id_progress01"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="50"
            hyman:progress_reach_color="#ffff0000"
            hyman:progress_text_color="#ffff0000"
            hyman:progress_unreach_color="#ff000000"
            android:padding="15dp"
            android:background="#44ff0000"
            android:layout_marginTop="30dp"
            />

        <myapplication4.xt.com.myapplication4.HorizontalProgressbarWithProgress
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="100"
            android:padding="5dp"
            hyman:progress_text_color="#44ff0000"
            hyman:progress_unreach_color="#ffff0000"
            android:layout_marginTop="30dp"
            />

        <myapplication4.xt.com.myapplication4.HorizontalProgressbarWithProgress
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="30"
            android:padding="5dp"
            hyman:progress_text_color="#44ff0000"
            hyman:progress_unreach_color="#ffff0000"
            android:layout_marginTop="30dp"
            />

    </LinearLayout>

</ScrollView>

MainActivity.java

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private HorizontalProgressbarWithProgress mHProgress;

    private static final int MSG_UPDATE=0x110;

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
                int progress=mHProgress.getProgress();
                mHProgress.setProgress(++progress);
                if(progress>=100){
                    mHandler.removeMessages(MSG_UPDATE);
                }
                mHandler.sendEmptyMessageDelayed(MSG_UPDATE,100);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHProgress= (HorizontalProgressbarWithProgress) findViewById(R.id.id_progress01);

        mHandler.sendEmptyMessage(MSG_UPDATE);

    }
}

Paste_Image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,368評論 25 708
  • ¥開啟¥ 【iAPP實現進入界面執行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,535評論 0 17
  • Android Studio JNI流程首先在java代碼聲明本地方法 用到native關鍵字 本地方法不用去實現...
    MigrationUK閱讀 11,953評論 7 123
  • 本書主要寫在那個動亂貧窮又無知的年代一個小人物許三觀賣血的故事。 許三觀第一次賣血,是跟爺爺村里的阿方和跟龍去的。...
    拾二余閱讀 768評論 0 1
  • 01 天朦朧,清晨霧霾依舊。 出門時,風帶著一絲寒意,撫醒了一臉的困意。抬手看一眼手表,八點一刻,匆匆忙忙趕往公交...
    月滿江白閱讀 375評論 0 2