Android Tutorial

(avery) #1
Android Tutorial 273

Drawing Rectangles with Rounded Corners

You can create rectangles with rounded corners, which can be nice
for making custom buttons. Simply create a ShapeDrawable from a
RoundRectShape object. The Round Rect Shape requires an array
of eight float values, which signify the radii of the rounded corners.
For example, the following creates a simple cyan-colored, rounded-
corner rectangle:

import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
...
ShapeDrawable rndrect = new ShapeDrawable(
new RoundRectShape( new float[] { 5, 5, 5, 5, 5, 5, 5, 5 },
null, null));
rndrect.setIntrinsicHeight(50);
rndrect.setIntrinsicWidth(100);
rndrect.getPaint().setColor(Color.CYAN);
ImageView iView = (ImageView)findViewById(R.id.ImageView1);
iView.setImageDrawable(rndrect);


The resulting round-corner rectangle is shown in Figure.

You can also specify an inner-rounded rectangle within the outer
rectangle, if you so choose. The following creates an inner
rectangle with rounded edges within the outer white rectangle with
rounded edges:

import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
...
float[] outerRadii = new float[]{ 6, 6, 6, 6, 6, 6, 6, 6 };
RectF insetRectangle = new RectF(8, 8, 8, 8);
float[] innerRadii = new float[]{ 6, 6, 6, 6, 6, 6, 6, 6 };
ShapeDrawable rndrect = new ShapeDrawable(new RoundRectShape(
outerRadii,insetRectangle , innerRadii));
rndrect.setIntrinsicHeight(50);
rndrect.setIntrinsicWidth(100);

Free download pdf