先上效果圖
然后上代碼(注釋應(yīng)該蠻清晰了吧,有需要隨便改改就能用咯)
public class ArcChart extends View {
//外部傳入的比例參數(shù)
private final float arrPer;
//RGB顏色數(shù)組 為漸變準(zhǔn)備為數(shù)組厕诡,起始顏色值和終止顏色值
private final int[] mMinColors = {Color.parseColor("#FF8359"), Color.parseColor("#FFDF40")};
public ArcChart(Context context, float getArrPer) {
super(context);
arrPer = getArrPer;
}
public void onDraw(Canvas canvas) {
DisplayMetrics dm = getResources().getDisplayMetrics();
int screenWidth = dm.widthPixels;//這里是控件view的寬度懒棉,設(shè)置為了屏幕寬度
float mMinOvalR = screenWidth / 6f; //圓環(huán)直徑
float mMinWidth = 90; //圓環(huán)寬度
float startAngle = 90;//圓弧起始角度
float degreeCircle = 180;//圓頭位置
float matrixStart = 90;//漸變旋轉(zhuǎn)角度
//創(chuàng)建畫筆:
Paint mMinPaint = new Paint();
mMinPaint.setColor(Color.parseColor("#F9F9F9"));
mMinPaint.setAntiAlias(true); //啟用抗鋸齒
mMinPaint.setDither(true); //啟用抗顏色抖動(可以讓漸變更平緩)
mMinPaint.setStyle(Paint.Style.STROKE);//圓弧
mMinPaint.setStrokeWidth(mMinWidth);//圓環(huán)寬度
//外接矩形
//算出矩形頂點坐標(biāo)涨冀。
RectF rect = new RectF(canvas.getWidth() / 2 - mMinOvalR,
canvas.getHeight() / 2 - mMinOvalR,
canvas.getWidth() - (canvas.getWidth() / 2 - mMinOvalR),
canvas.getHeight() - (canvas.getHeight() / 2 - mMinOvalR));
canvas.drawArc(rect, 0, 360, false, mMinPaint);//先畫一圈背景灰色圓環(huán)
float degree = 360 * (arrPer / 100); //圓弧掃過的角度
matrixStart += degree;//漸變旋轉(zhuǎn)角度要開始計算
//創(chuàng)建漸變
SweepGradient mSweepGradient = new SweepGradient(canvas.getWidth() / 2,
canvas.getHeight() / 2,
mMinColors,
new float[]{0f, degree});
Matrix matrix = new Matrix();//將漸變旋轉(zhuǎn)
matrix.setRotate(matrixStart, canvas.getWidth() / 2, canvas.getHeight() / 2);
mSweepGradient.setLocalMatrix(matrix);
//把漸變設(shè)置到筆刷
mMinPaint.setShader(mSweepGradient);
//畫漸變的弧
canvas.drawArc(rect, startAngle, degree, false, mMinPaint);
//記錄下位置
float[] arrayInt = {0, arrPer};
//獲取漸變弧結(jié)束點的顏色值和漸變的開始值
int[] newColor = {Color.rgb(255,
(int) (223 + (-0.92 * arrPer)), (int) (64 + (0.25 * arrPer))), mMinColors[1]};
//畫圓弧開始和結(jié)束的圓點
for (int i = 0; i < 2; i++) {
Paint mMinCirclePaint = new Paint();//定義頭部畫筆
mMinCirclePaint.setColor(newColor[i]);//取顏色值
mMinCirclePaint.setAntiAlias(true);//啟用抗鋸齒
degreeCircle += 360 * (arrayInt[i] / 100); //圓位置等于圓弧長度
float mDegreeCircle = degreeCircle - 90;//抵消屏幕坐標(biāo)系差異
mDegreeCircle = (float) (Math.PI / 180f * mDegreeCircle); //換成弧度
canvas.drawCircle((float) (rect.left + rect.width() / 2f + mMinOvalR * Math.cos(mDegreeCircle)), //圓心x
(float) (rect.top + rect.height() / 2f + mMinOvalR * Math.sin(mDegreeCircle)), //圓心y
mMinWidth / 2f, //半徑
mMinCirclePaint);
}
}
}
使用的時候直接new ArcChart(this, 0.5f);就行啦
主要是用SweepGradient來疊加漸變色劳闹,但是我發(fā)現(xiàn)似乎少于360度的圓弧無法根據(jù)傳入的顏色值進行完全的漸變碾牌,所以我上面代碼只能通過獲取圓弧結(jié)束點的顏色值來達到結(jié)束點的圓角效果
要是有人知道怎么解決這個問題麻煩留言告知一下哦