Confusingly there’s also ShapeDrawable, which the Android documentation and training guide claims to be defined in xml with <shape> element. This is not right and one can look at ShapeDrawable source code to confirm that.
The following screenshot captures what can be done with GradientDrawable. The source can be found here.
Figure 1. Drawings Generated by Android GradientDrawable
And the table below shows some elements are not available for certain shapes.
We’ll first introduce the four shapes, and then go through some of the important xml elements.
There’s not much use when shape is line, because lots of elements are not supported and all the effects we want to draw with line shape can be done with rectangle.
One thing to note that is when specifying a dashed stroke, it won’t work properly due to bug here. Suppose we’re drawing the line on ImageView, the following code is needed.
Rectangle is used to draw a rectangle-like shape. It’s the only shape can have corners elements, which makes it very powerful. The corners element allows one to specify the radius at four corners of the rectangle.
One can use rectangle shape to draw a line by specifying a small height, or draw a circle by specifying proper corner radius.
Oval can be used to draw a circle or oval.
innerRadius is used to specify the width of the inner hole of the ring. innerRadiusRatio is to specify the innerRadius as the ratio of the ring’s width. For example, innerRadiusRatio=”5” means innerRadius is equal to the ring’s width divide by 5.
Thickness defines the thickness of the ring. thicknessRatio is similar to innerRadiusRatio.
There are three gradient types supported, namely linear, radial and sweep. One can refer to figure 1 for the drawing can be created by them.
All gradients must specify startColor and endColor. centerColor is optional and its relative position is also configurable via centerX and centerY (both in range of (0, 1.0)).
A linear gradient, which specifies a starting gradually transforms into ending color. It is also the default gradient. Linear gradient has a special attribute named angle. It must be a multiple of 45 and in the range of [0, 315].
Figure 2. Angle of Linear Gradient
Radial defines a gradient in a fan out fashion. It has a special attribute gradientRadius, which must be defined.
Padding is applied to the containing View element (this pads the position of the View content, not the shape).
For example, if this oval is set to the background of an ImageView, and the paddings will be applied to position the image resource (view content) of the image view.
Defines the shape’s width and height. The shape scales to the size of the container View proportionate to the dimensions defined here by default. When you use the shape in an ImageView, you can restrict scaling by setting the android:scaleType to “center”.