【Android】 利用Shape畫出漸層的ProgressBar

最近在使用ProgressBar時,發現原本的ProgressBar有點單調,只有單個顏色。那要如何做出有顏色漸層效果的Progress? 其實Android提供很好用的方式:Shape就可以做出有漸層效果的Progress bar。首先在res/drawable 下新增progressbarstyle.xml

以下為parameter說明:
Android 提供五種shape:rectangle(矩形)、oval(橢圓)、line(直線)、ring(圓環)。

而ProgressBar須選擇ring(圓環)。而當你使用ring後,會有以下五個parameter可使用
可參考以下這篇的解釋:[Shape Drawable的學習]

以下為此篇五個參數對五個參數的說明:- innerRadius : 指定圓環內圓的半徑,比如50dp、100dp之類的。- innerRadiusRatio : 該值是以比例的形式來指定內圓半徑。內圓半徑等於該shape的寬除以該值。或者說該值的倒數代表了內圓半徑佔整個shape寬的比例。默認值是9。當該值等於2的時候,內圓就將佔滿整個shape,從而我們將看不到圓環。- thickness : 指定圓環的寬窄,也就是內圓與外圓的距離。- thicknessRatio : 以比例的形式來指定圓環的寬窄。其算法與innerRadiusRatio相同。- useLevel : 值為true意味著這是一個levelListDrawable(關於levelListDrawable又是另一個話題了)。當我們要畫一個圓環是,應當而且必須將該值設為false,否則會看不到畫面。

這邊我是使用innerRadiusRatio與thicknessRatio此兩個參數來設定內環與外環的比率。當然亦可以全部使用。
最後一個參數android:useLevel,一定要設為false才可以看到畫面

gradient- android:angle - 必須為45的倍數,0表示從左到右,90表示從上到下。- android:endColor - 漸變結束的顏色- android:startColor - 漸變開始的顏色- android:centerColor - 漸變中間的顏色- android:type - ["linear" | "radial" | "sweep"] 共有3種漸變類型,線性(default)、放射漸變、掃描式漸變,這邊我使用sweep

以下為實際使用的截圖

Android 提供的Shape真的可以用在很多地方,尤其是對custom view的部分,可以節省很多時間喔!

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade