Android GradientDrawable

We will use .9.png to set up background in general.
Besides using png, we can use shape tag to set up background.

GradientDrawable

Static Method

Create xml file in drawable folder.

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”]

The shape type, default type is rectangle, it can change to oval, line or ring.

android:radius

Gradient Color
android:startColor :
android:centerColor :
android:endColor:

android:useLevel
true: no gradient color
false: has gradient color

android:angle

The angle for the gradient, in degrees.
0 is left to right, 90 is bottom to top.
It must be a multiple of 45.
Default is 0.

android:type : gradient style [linear | radial | sweep]


linear (default style)


radial


sweep

android:centerX, android:centerY : The relative position

Value is from 0.0 to 1.0. In this case we set the point in center, so android:centerX and android:centerY are 0.5。

android:gradientRadius

When android:type=radial,it must setup this item, otherwise you will get the XmlPullParserException.

Dynamic Method

Setup shage in xml, it is change to GradientDrawable, not
ShapeDrawable or OvalShape,RoundRectShape and so on.

Source code as follows (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 is deprecated in Kotlin, you must use GradientDrawable.Orientation.* to implamemnt.

1
gd.orientation = GradientDrawable.Orientation.TOP_BOTTOM

RunningTime Update

We can change background by using GradientDrawable at running time.

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)
Author

Nick Lin

Posted on

2018-08-07

Updated on

2023-01-18

Licensed under


Comments