Use Shape Drawables Android

Tram Ho

Why use ShapeDrawable

When we use PNG or JPEG images in an app, we will need to have multiple copies of them depending on screen resolution. Because of that, it will increase the size of the app. Of course for special cases we need to use images, but in some cases we should use ShapeDrawable instead, which will greatly reduce the size of the application.

For example, with the buttons in the image below, we can use the image to set it as that background, but we should use ShapeDrawable.

What is ShapeDrawable?

ShapeDrawable is a collection of commands that help to draw certain shapes with custom sizes and colors without changing the image quality.

Create a ShapeDrawable in XML

First we will create a drawable resource file.

Right click res / drawable> New> Drawable resource file> Enter file name> use shape as root element> Click Ok

A sample file will have a format like this:


Attributes when creating a shape

1. Shape type

Defines the type of shape to be drawn. If we do not define the shape type then default it will be rectangle, in addition it also provides other shapes like oval, line and ring.

2. Rounded Coneres

Defines the rounded corners of a rectangle when we use the rectangle shape type.

We can also stroke in every rectangle with the attributes: android: topLeftRadius, android: topRightRadius, android: bottomLeftRadius, android: bottomRightRadius

3. Gradient or Solid color

Defines the background color of the shape, be it gradient or solid.If you want to use solid color, we add the solid tag and add the color attribute to define it.

If we want to use gradient colors, we’ll add a gradient tag and define the start, center, and end colors

If you do not define the type of the gradient it will leave the type as linear by default, in addition to other types such as radial, sweep.

If we want to change the angle, the gradient direction, we will change the angel attibute. For example, we give the gradient from bottom left to top right corner, we will set angel with value 45

4. Size

Defines the size of the shape to use for specific situations

5. Stroke

Define the border of the shape with width and color, to define the dash distance and the width of the dash we use dashGap and dashWidth.

Use the shape in View

After we have created the drawable file, we use it in the view as follows

Instead of using android: background , we can use:

Use on Java:

Editing the shape in Java

We can also edit the shape drawable with java


Thank you for reading the article, hope it helps you.


Share the news now

Source : Viblo