Thursday, February 21, 2013

Android beginner tutorial: Part 89 - ShapeDrawable shapes

Today we'll learn about drawing shapes in Android using the ShapeDrawable class.

If you want to dynamically draw 2d shapes, the ShapeDrawable class might be what you're looking for. Similar to the Flash Drawing API used in Actionscript 3, this Android gives us the ability to draw and stylize simple primitive shapes.

There is a set of classes extended from Shape, which we can use to create different shapes. These classes are PathShape, RectShape, ArcShape, OvalShape and RoundRectShape.

The ShapeDrawable class is an extension of Drawable, so it can be used just like any other Drawable object. When drawing in a ShapeDrawable - remember to set the color and the boundaries of the object. If the color is not specified - black will be used by default. If the boundaries are not set - the drawing will not be visible.

Firstly, let's see how to draw lines with this. There isn't a separate class for displaying lines, but there's RectShape, which can work as lines too if we make them thing enough.


ShapeDrawable shape = new ShapeDrawable(new RectShape());

An oval is drawn similarly to a rectangle. Simply set the width and height:

ShapeDrawable shape = new ShapeDrawable(new OvalShape());

Drawing rounded rectangles is a little bit more complex, but not hard at all. The RoundRectShape constructor has 3 parameters - outerRadii, inset and innerRadii.

The outerRadii value is an array of float values that represent the radii of each corner. Each corner has 2 radii, so there are 8 values in total. The first 2 values are the radii of the top left corner, each next 2 correspond to the next corner clockwise. If you don't want rounded corners, pass null.

The inset value is a RectF class object, which represents the distance between the inner rectangle and the outer one. The constructor of the RectF class has 4 parameters - pairs of coordinates (x and y) of top left corner and bottom right corner of the inner rectangle. If there's no inner rectangle, pass null.

The innerRadii value is an array of radii for the corners of the inner rectangle. Works the same way as outerRadii.

A simple example:

float[] outR = new float[] {6, 6, 6, 6, 6, 6, 6, 6};
RectF rectF = nwe RectF(8, 8, 8, 8);
float[] inR = new float[] {6, 6, 6, 6, 6, 6, 6, 6};

ShapeDrawable shape = new ShapeDrawable(new RoundRectShape(outR, rectF, inR));

That's all for today. Next time we'll look at more shapes to draw.

Thanks for reading!

No comments:

Post a Comment