Softening the Edges, or at Least the Corners

You know that the standard Java distribution includes a class called

Rectangle used for defining shapes with four sides and four right

angles (that includes regular squares as well as stretched rectangles).

The standard distribution -- the java.awt.geom package, specifically --

includes a similar class called RoundRectangle2D.Float. An instance of

RoundRectangle2D.Float is like a an instance of Rectangle, but with

rounded corners instead of 90-degree ones.

As with a standard Rectangle, you declare an instance of

RoundRectangle2D.Float with four numbers defining the coordinates,

in pixels, of its top-left and bottom-right corners. In most cases --

if there's any point to declaring a RoundRectangle at all -- the actual

corner points will be essentially imaginary and not actually rendered

if the shape is drawn. They'll exist somewhere outside the curves

joining each pair of sides.

So, when defining a RoundRectangle.Float instance, we must specify

points for the curves beginning. Two values, in addition to the four

defining the "corners," specify how far back from the would-be

corners the curve starts. The first value (the fifth argument you send

to the setRoundRect() method) represents the horizontal offset while

the second value is the vertical offset. Both values are in pixels, as

usual.

Typically, the code for declaring and sizing a RoundRectangle.Float

instance will look something like this:

RoundRectangle2D rect = new RoundRectangle2D.Float();

rect.setRoundRect(20f,60f,160f,80f,20f,20f);

That code specifies a rectangle with corners that break 20 pixels back

(both horizontally and vertically) from the points at which the sides

would intersect if extended.

Here's a working example for you.

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.*;

class RoundRect extends Frame {

public static void main(String arg[]) {

new RoundRect();

}

RoundRect() {

super("RoundRect");

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e)

{ System.exit(0); } } );

setSize(440,440);

show();

}

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D)g;

RoundRectangle2D rect = new RoundRectangle2D.Float();

rect.setRoundRect(20f,60f,160f,80f,20f,20f);

g2.draw(rect);

rect.setRoundRect(200f,60f,120f,120f,24f,24f);

g2.draw(rect);

rect.setRoundRect(340f,60f,80f,160f,20f,44f);

g2.draw(rect);

rect.setRoundRect(20f,260f,160f,80f,20f,20f);

g2.fill(rect);

rect.setRoundRect(200f,260f,120f,120f,28f,28f);

g2.fill(rect);

rect.setRoundRect(340f,260f,80f,160f,20f,44f);

g2.fill(rect);

}

}

Top 10 Hot Internet of Things Startups
Join the discussion
Be the first to comment on this article. Our Commenting Policies