先看效果圖:
這就是miui中的音量效果圖,實現思路是自定義視圖,繪制圓環,然后設置進度顯示。
核心代碼在onDraw中實現如下:
@Override protected void onDraw(Canvas canvas) { float cx = getMeasuredWidth() / 2; float cy = getMeasuredHeight() / 2; r1 = cx - w1 / 2; r2 = cx - w1 / 2 - w2 / 2; r3 = cx - w1 / 2 - w2; // 繪制外圓 paint.setStrokeWidth(w1); paint.setColor(Color.parseColor("#454547")); canvas.drawCircle(cx, cy, r1, paint); // 繪制中間圓環 paint.setColor(Color.parseColor("#747476")); paint.setStrokeWidth(w2); canvas.drawCircle(cx, cy, r2, paint); // 繪制內圓 paint.setColor(Color.parseColor("#464648")); paint.setStyle(Style.FILL); canvas.drawCircle(cx, cy, r3, paint); // 繪制中間的圖片 canvas.drawBitmap(bitmap, cx - bitmap.getWidth() / 2, cx - bitmap.getHeight() / 2, paint); // 繪制文本 paint.setColor(Color.WHITE); paint.setStrokeWidth(0); paint.setTextSize(40); float textWidth = paint.measureText("鈴聲"); // 測量字體寬度,我們需要根據字體的寬度設置在圓環中間 canvas.drawText("鈴聲", cx - textWidth / 2, cx + bitmap.getHeight() / 2 + 40, paint); // 繪制進度 paint.setStyle(Style.STROKE); paint.setStrokeWidth(w2); paint.setColor(Color.WHITE); RectF oval = new RectF(cx - r2, cy - r2, cx + r2, cy + r2); // 用於定義的圓弧的形狀和大小的界限 canvas.drawArc(oval, 270, 360 * progress / 100, false, paint); super.onDraw(canvas); }
然后就是自定義toast,加載上面的自定義控件。
public class VolumnController { Toast t; VolumnView tv; Context context; public VolumnController(Context context) { this.context = context; } public void show(float progress) { if (t == null) { t = new Toast(context); View layout = LayoutInflater.from(context).inflate(R.layout.vv, null); tv = (VolumnView) layout.findViewById(R.id.volumnView1); t.setView(layout); t.setGravity(Gravity.BOTTOM, 0, 100); t.setDuration(Toast.LENGTH_SHORT); } tv.setProgress(progress); t.show(); } }
最后附上所有的源碼:點擊我!!!