Android GradientDrawable 漸變效果
一般我們繪製背景圖時,會使用.9.png來設置。遇到漸層背景時,除了透過.9.png設置之外,還可以使用Android本身所提供的shape標籤來實現。
GradientDrawable
靜態使用
在drawable中創建一個xml文件
1 |
|
android:shape = [“rectangle” | “oval” | “line” | “ring”]
shape形狀,默認為矩形 rectangle,亦可設置橢圓形oval、線性line、環形ring
android:radius : 圓角大小
漸變顏色
android:startColor : 起始顏色
android:centerColor : 中間值顏色,從起始顏色到結束顏色的變化過程中的中繼顏色
android:endColor: 結束顏色
android:useLevel : true (無漸變) | false (有漸變)
android:angle : 漸變角度
以45度為一個單位。
0 - 由左至右 ; 90 - 由下至上 ; 180 - 由右至左 ; 270 - 由上至下
android:type : 漸變樣式 [linear | radial | sweep]
linear 線性漸變 (默認設置)
radial 放射式漸變
sweep 雷達式漸變、掃描線式漸變
android:centerX, android:centerY : 中心點相對位置
值域從 0.0 ~ 1.0,此案例設定在中心點,所以 android:centerX和 android:centerY皆為0.5。
android:gradientRadius: 漸變色半徑
當設定android:type=radial 時,一定要設定此項目,否則會發生XmlPullParserException。
動態使用
使用xml來設定shape,最終都是轉成GradientDrawable,並非為ShapeDrawable, 也不是 OvalShape,RoundRectShape等。
程式設計如下:(使用Kotlin語法)
1 | var imageView = findViewById<ImageView>(R.id.photo) |
android:angle 在 Kotlin中已被取消,必須透過GradientDrawable.Orientation.* 來達成功能。
如:
1 | gd.orientation = GradientDrawable.Orientation.TOP_BOTTOM |
動態更改
既然我們可以動態配置GradientDrawable,那也可以透過動態修改來改變其背景。相關設定如下
1 | var imageView = findViewById<ImageView>(R.id.photo) |
Android GradientDrawable 漸變效果
https://nickcarter9.github.io/2018/08/07/2018/2018_08_07-gradientdrawable/