Graphics Stroking

The Graphics2D method setStroke() is yet another method for changing the graphics context. We will now examine graphics stroking in greater detail.

Whenever a shape is stroked, it is as if a virtual pen draws an outline around the shape. The virtual pen has a characteristic style defining a set of shape primitives that are combined to make the desired effect. In Java 2D, the pen style is specified in a BasicStroke object. BasicStroke implements the Stroke interface and is intended to be used as an argument to the setStroke() method of the Graphics2D object.

The BasicStroke object represents the attributes for line width, endcap, and join style in addition to attributes for specifying different types of dash patterns. Setting the Stroke attributes will affect most of the rendering methods such as draw(), drawArc(), and so on.

One of the most basic examples of needing to change the Stroke attribute is in controlling the line thickness for drawing. Let's once again return to the BasicRecipeJ2D class. In this case, we will change the rendering context through the setStroke() method. For brevity, only the particular code for changing the context is included.

BasicStroke stroke = new BasicStroke(10);
g2d.setStroke(stroke);

Another common need is to set a dash pattern for the stroke. In this case, use the BasicStroke constructor with six arguments:

g2d.setStroke(new BasicStroke(8.0f,
                              BasicStroke.CAP_BUTT,
                              BasicStroke.JOIN_BEVEL,
                              8.0f,
                              new float[] {10.0f, 4.0f},
                              0.0f);

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset