天天看點

Android中自定義View漸變色進度條

參考網址:https://www.jb51.net/article/140249.htm

package com.customview.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.Paint.Cap;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import com.customview.R;

public class GoodProgressView extends View
{
	private int[] mColors = { Color.RED, Color.MAGENTA};//進度條顔色(漸變色的2個點)
	private int backgroundColor = Color.GRAY;//進度條預設顔色
	private int textColor = Color.GRAY;//文本顔色
    
	private Paint mPaint;//畫筆
	private int progressValue=0;//進度值
//	private RectF rect;//繪制範圍
				
	public GoodProgressView(Context context, AttributeSet attrs)
	{		
		this(context, attrs, 0);
	}

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

	// 獲得我自定義的樣式屬性 
	public GoodProgressView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		
		// 獲得我們所定義的自定義樣式屬性 
		TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.GoodProgressView, defStyle, 0);
		int n = a.getIndexCount();
		for (int i = 0; i < n; i++)
		{
			int attr = a.getIndex(i);
			if (attr==R.styleable.GoodProgressView_startColor){
                // 漸變色之起始顔色,預設設定為紅色
                mColors[0] = a.getColor(attr, Color.RED);
            }else if (attr==R.styleable.GoodProgressView_endColor){
                // 漸變色之結束顔色,預設設定為品紅
                mColors[1] = a.getColor(attr, Color.MAGENTA);
            }else if (attr==R.styleable.GoodProgressView_gpv_backgroundColor){
                // 進度條預設顔色,預設設定為灰色
                backgroundColor = a.getColor(attr, Color.GRAY);
            }else if (attr==R.styleable.GoodProgressView_gpv_textColor){
                // 文字顔色,預設設定為灰色
                textColor = a.getColor(attr, Color.GRAY);
            }
		}
		a.recycle();

		mPaint = new Paint();
		progressValue=0;
	}
	
	public void setProgressValue(int progressValue){

		if(progressValue>100){
			progressValue = 100;
		}
		this.progressValue = progressValue;
		Log.i("customView","log: progressValue="+progressValue);
	}

	public void setColors(int[] colors){
		mColors = colors;	
	}
	//在ScrollView中使用自定義View需要重寫該方法	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
		int width = 0;
		int height = 0;
		/**
		 * 設定寬度
		 */
		int specMode = MeasureSpec.getMode(widthMeasureSpec);
		int specSize = MeasureSpec.getSize(widthMeasureSpec);
		switch (specMode)
		{
		case MeasureSpec.EXACTLY:// 明确指定了
			width = specSize;
			break;
		case MeasureSpec.AT_MOST:// 一般為WARP_CONTENT
			width = getPaddingLeft() + getPaddingRight() ;
			break;
		}

		/**
		 * 設定高度
		 */
		specMode = MeasureSpec.getMode(heightMeasureSpec);
		specSize = MeasureSpec.getSize(heightMeasureSpec);
		switch (specMode)
		{
		case MeasureSpec.EXACTLY:// 明确指定了
			height = specSize;
			break;
		case MeasureSpec.AT_MOST:// 一般為WARP_CONTENT
			height = width/10;
			break;
		}
		
		Log.i("customView","log: w="+width+" h="+height);
		setMeasuredDimension(width, height);

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

		int mWidth = getMeasuredWidth();
		int mHeight = getMeasuredHeight();
		
		//按比例計算進度條各部分的值
		float unit = Math.min(((float)mWidth)/300, ((float)mHeight)/30);
		float lineWidth = 5*unit;//線粗
		float innerCircleDiameter = 6*unit;//内圓直徑
		float outerCircleDiameter = 10*unit;//外圓直徑
		float wordHeight = 12*unit;//字高//9*unit
//		float wordWidth = 26*unit;//字長
		float offsetLength = 5*unit;//留白
//		float width = 300*unit;//繪畫區域的長度
		float height = 30*unit;//繪畫區域的高度
		float progressWidth = 258*unit;//繪畫區域的長度


		mPaint.setAntiAlias(true);
		mPaint.setStrokeWidth((float) lineWidth );
		mPaint.setStyle(Style.STROKE);
		mPaint.setStrokeCap(Cap.ROUND);
		
		mPaint.setColor(Color.TRANSPARENT);

		float offsetHeight=height/2;
		float offsetWidth=offsetLength;
		
		float section = ((float)progressValue) / 100;
		if(section>1)
			section=1;
		
		int count = mColors.length;
		int[] colors = new int[count];
		System.arraycopy(mColors, 0, colors, 0, count);			

	
		//底部灰色背景,訓示進度條總長度
		mPaint.setShader(null);
		mPaint.setColor(backgroundColor);	
		canvas.drawLine(offsetWidth+section * progressWidth, offsetHeight, offsetWidth+progressWidth, offsetHeight, mPaint);
		
		//設定漸變色區域
		LinearGradient shader = new LinearGradient(0, 0, offsetWidth*2+progressWidth , 0, colors, null,
				Shader.TileMode.CLAMP);
		mPaint.setShader(shader);

		//畫出漸變色進度條
		canvas.drawLine(offsetWidth, offsetHeight, offsetWidth+section*progressWidth, offsetHeight, mPaint);
	
		//漸變色外圓
        mPaint.setStrokeWidth(1);
        mPaint.setStyle(Paint.Style.FILL);
		canvas.drawCircle(offsetWidth+section * progressWidth, offsetHeight, outerCircleDiameter/2, mPaint);


		//繪制兩條斜線,使外圓到進度條的連接配接更自然
		if(section*100>1.8){
			
			mPaint.setStrokeWidth(2*unit);
			canvas.drawLine(offsetWidth+section * progressWidth-6*unit, offsetHeight-(float)1.5*unit, 
					offsetWidth+section * progressWidth-1*unit,offsetHeight-(float)3.8*unit, mPaint);
			
			canvas.drawLine(offsetWidth+section * progressWidth-6*unit, offsetHeight+(float)1.5*unit, 
					offsetWidth+section * progressWidth-1*unit,offsetHeight+(float)3.8*unit, mPaint);
		}
		
		//白色内圓
		mPaint.setShader(null);
		mPaint.setColor(Color.WHITE);
		canvas.drawCircle(offsetWidth+section * progressWidth, offsetHeight, innerCircleDiameter/2, mPaint);//白色内圓

		
		//繪制文字--百分比
		mPaint.setStrokeWidth(2*unit);
		mPaint.setColor(textColor);
		mPaint.setTextSize(wordHeight);
		//計算坐标使文字居中
		FontMetrics fontMetrics = mPaint.getFontMetrics();  
		float  fontHeight = fontMetrics.bottom - fontMetrics.top;
		float baseY =  height/2 + fontHeight/2 - fontMetrics.bottom;
		canvas.drawText(""+progressValue+"%", progressWidth+2*offsetWidth, baseY, mPaint);//略微偏下,baseline
	
	}
		
}
           

res/values/attr.xml

<declare-styleable name="GoodProgressView">
        <attr name="startColor" format="color"/>
        <attr name="endColor" format="color"/>
        <attr name="gpv_backgroundColor" format="color"/>
        <attr name="gpv_textColor" format="color"/>
    </declare-styleable>
           

布局中使用

<com.customview.view.GoodProgressView 
android:id="@+id/good_progress_view1" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:padding="10dp"/>
           

代碼中指定漸變色

good_progress_view1 = (GoodProgressView)findViewById(R.id.good_progress_view1);
good_progress_view2.setColors(randomColors());

//随機生成顔色
    private int[] randomColors() {
        int[] colors=new int[2];
        Random random = new Random();
        int r,g,b;
        for(int i=0;i<2;i++){
            r=random.nextInt(256);
            g=random.nextInt(256);
            b=random.nextInt(256);
            colors[i]= Color.argb(255, r, g, b);
        }
        return colors;
    }
           

繼續閱讀