Android GradientDrawable 漸變效果

一般我們繪製背景圖時,會使用.9.png來設置。遇到漸層背景時,除了透過.9.png設置之外,還可以使用Android本身所提供的shape標籤來實現。

GradientDrawable

靜態使用

在drawable中創建一個xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<size
android:width="200dp"
android:height="200dp"/>
<corners
android:radius="10dp"/>

<gradient
android:startColor="@android:color/white"
android:centerColor="@android:color/holo_red_light"
android:endColor="@android:color/black"
android:useLevel="false"
android:angle="90"
android:type="radial"
android:centerX="0.5"
android:centerY="0.5"
android:gradientRadius="50"/>
</shape>

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
2
3
4
5
6
7
8
9
10
11
12
var imageView = findViewById<ImageView>(R.id.photo)

var gd = GradientDrawable()
gd.gradientType = GradientDrawable.RECTANGLE //android:shape
gd.cornerRadius = 10.0F //android:radius
gd.colors = intArrayOf(Color.WHITE, Color.RED, Color.BLACK) //android:centerColor, android:startColor, android:endColor
gd.useLevel = false //android:useLevel
gd.gradientType = GradientDrawable.RADIAL_GRADIENT //android:type
gd.setGradientCenter(0.5F, 0.5F) //android:centerX, android:centerY
gd.gradientRadius = 50.0F //android:gradientRadius

imageView.background = gd

android:angle 在 Kotlin中已被取消,必須透過GradientDrawable.Orientation.* 來達成功能。

如:

1
gd.orientation = GradientDrawable.Orientation.TOP_BOTTOM

動態更改

既然我們可以動態配置GradientDrawable,那也可以透過動態修改來改變其背景。相關設定如下

1
2
3
var imageView = findViewById<ImageView>(R.id.photo)
var gd = imageView.background as GradientDrawable
gd.colors = intArrayOf(Color.WHITE, Color.BLUE, Color.BLACK)
作者

Nick Lin

發表於

2018-08-07

更新於

2023-01-18

許可協議


評論