Sunday, January 18, 2015
Android beginner tutorial Part 89 ShapeDrawable shapes
Today well learn about drawing shapes in Android using the ShapeDrawable class.If you want to dynamically draw 2d shapes, the ShapeDrawable class might be what youre 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, lets see how to draw lines with this. There isnt a separate class for displaying lines, but theres RectShape, which can work as lines too if we make them thing enough.
Example:
ShapeDrawable shape = new ShapeDrawable(new RectShape());
shape.setIntrinsicHeight(2);
shape.setIntrinsicWidth(200);
shape.getPaint().setColor(Color.RED);
An oval is drawn similarly to a rectangle. Simply set the width and height:
ShapeDrawable shape = new ShapeDrawable(new OvalShape());
shape.setIntrinsicHeight(100);
shape.setIntrinsicWidth(200);
shape.getPaint().setColor(Color.RED);
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 dont 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 theres 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));
shape.setIntrinsicHeight(100);
shape.setIntrinsicWidth(200);
shape.getPaint().setColor(Color.RED);
Thats all for today. Next time well look at more shapes to draw.
Thanks for reading!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment