- The Basic Java 2D Recipe
- Set the Graphics2D Context...
- ...and Render Something
- Rendering on Components
- Shape Primitives
- Graphics Stroking
- Fill Attributes and Painting
- Transparency and Compositing
- Text
- Clipping
- Coordinate Space Transformations
- Techniques for Graphical User Input
- Double Buffering
- Comprehensive Example: Kspace Visualization
- Summary
Fill Attributes and Painting
Assigning material for painting is done by creating a Paint object (specifically, an object implementing the Paint interface) and adding it to the Graphics2D context with the setPaint() method. As you will see next, three general types of Paint objects already exist and are easily instantiated. Any of these can readily be used as arguments to setPaint(). Before going into these three general types, it is worthwhile to understand the Paint interface and how it relates to a second interface, the PaintContext interface. An understanding of these two interfaces will be useful when we discuss custom painting later.
The Paint interface consists of a unitary method that returns a PaintContext:
PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Recangle2D userBounnds, AffineTransform xform, RenderingHints hints);
The relationship between Paint and PaintContext is easily understood if you are comfortable with the concepts of user space and device space described in the introduction to this section.
The Paint and PaintContext are related in the following way:
The Paint object operates in user space. It specifies the way that color patterns are handled by Graphics2D operations. The PaintContext operates in device space and defines how color patterns are handled by specific devices. Accordingly, Paint and PaintContext are device dependent and independent, respectively.
Whenever a Paint object is instantiated, a PaintContext containing (encapsulating) the information necessary for putting color patterns on each output device is automatically set up. The two primary components of a PaintContext are a Raster (as mentioned previously, a rectangular array of pixel values in device space) and a ColorModel.
The ColorModel, described briefly in the introduction to this section and covered in detail in Chapter 6, "Java Advanced Imaging," specifies how raw pixel values are interpreted as colors. Again, RGB is the most common ColorModel used, but many varieties exist.
The deviceBounds and userBounds arguments to Paint's creatContext() method specify the bounding box of the primitive being rendered in device space and user space, respectively. By placing the appropriate restrictions on the bounds being painted, considerable improvement in runtime can be achieved.
The AffineTransform object specifies the transform between user space and device space. Together, AffineTransform, deviceBounds, and userBounds are used to specify the ultimate Raster object that is used in device space.
The last argument, RenderingHints, is the same class that you saw previously when setting other aspects of the rendering context, and likewise represents a set of options for rendering, particularly those that make a tradeoff of quality and speed. Note that the specific RenderingHints that are designated when generating a PaintContext are different from those used when describing Shapes. Regardless, all rendering hints are grouped together under the same general heading.
Given this background on the Paint and PaintContext interfaces, we are in a good position to understand the standard Paint objects that can be added to the Graphics2D context as well as the potential to create our own Paint objects in case the standard objects aren't sufficient for a given application.
Preexisting Paint Objects
As mentioned, Java 2D already provides three classes that implement the Paint interface. By and large, these three classes are sufficient for most applications.
Solid Color Painting
The simplest Paint object (and the object used in all the examples so far) is the Color object. There are numerous constructors for the Color object; however, some examples of the most commonly used are
Color red = new Color.red; //use the Color.* for predefined colors; //specify RGB values between 0 and 1; Color red = new Color(1.f,0.f,0.f);
It is also possible to specify an alpha value for transparency.
For example,
Color.red = new Color(1.f,0.f,0.f,.5f);
Specifies a transparency of .5. Many more options can be specified with the AlphaComposite object (see "Transparency and Compositing").
Using your deeper understanding of Paint and PaintContext, let's examine the steps that occur within a simple solid color paint.
First, a ColorModel is created. The ColorModel used is most often the ColorModel specified in RenderingHints. However, a different ColorModel from the one specified might occasionally occur because a given device might not use the specified ColorModel. Regardless, one way or the other, a device dependent ColorModel is selected for rendering.
Second, a Raster is generated that contains pixel values for the output device. Remember from Chapter 2, "Imaging and Graphics on the Java Platform," a Raster is a rectangular array of pixel values. In this simple case in which a solid color is desired, all pixels of our Raster have the same value. In the case of GradientPaint and TexturePaint (described next), the pixels have different values. You will see in the GradientPaint example in Listing 3.4 that the PaintContext's getRaster() method can be used to get an instance of the Raster that we can manipulate in whatever fashion we desire.
Finally, after it is no longer needed, the PaintContext object is disposed by calling System.dispose().
Gradient Paints
GradientPaint is the second object implementing the Paint interface and, like all paint objects, can be added to the Graphics2D context with setPaint(). A gradient paint is commonly used in practice and represents a transition between two colors. In order to make a GradientPaint object, it is necessary to specify the starting and ending points for the transition (see Figures 3.4, 3.5, 3.6, and 3.7), the two colors to use, as well as an optional rule to specify how the paint looks outside the region specified by the starting and ending points. The outer zone can be either cyclic (repeats outside the start and endpoints) or acyclic (remains at the final value of the gradient outside the start and endpoints).
Listing 3.4 demonstrates the options that can be specified for a GradientPaint.
Listing 3.4 GradientPaintEx.java
. . . import java.lang.StrictMath; public class GradientPaintEx extends JFrame { myCustomCanvas mc; JSlider p1slide, p2slide; JRadioButton cyclic_rb, acyclic_rb; public GradientPaintEx() { super("GradientPaint examples"); BorderLayout f1 = new BorderLayout(); //layout manager for the frame mc = new myCustomCanvas(this); mc.setSize(500,500); . . . mc.setPaint(100,200); addWindowListener(new WindowEventHandler()); } class WindowEventHandler extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } public static void main(String[] args) { new GradientPaintEx(); } } class SliderListener implements ChangeListener { GradientPaintEx gex; myCustomCanvas mc; int slider_val; public SliderListener(GradientPaintEx gex, myCustomCanvas mc) { this.gex = gex; this.mc = mc; } public void stateChanged(ChangeEvent e) { int p1pos = gex.p1slide.getValue(); int p2pos = gex.p2slide.getValue(); mc.setPaint(p1pos,p2pos); }//End of stateChanged }//End of SliderListener class myCustomCanvas extends Canvas { GradientPaintEx gex; double p1pos, p2pos; GradientPaint gpaint; public myCustomCanvas(GradientPaintEx gex) { this.gex = gex; } public void setPaint(int p1pos, int p2pos) { this.p1pos = (double) p1pos; this.p2pos = (double) p2pos; boolean cycle = true; if (gex.cyclic_rb.isSelected()) cycle = true; else cycle = false; Point x = new Point2D.Double(p1pos, this.getSize().height/2), Point y = new Point2D.Double(p2pos, this.getSize().height/2), gpaint = new GradientPaint(x, y, Color.red, Color.green,cycle); repaint(); } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { gex.p1slide.setMaximum(this.getSize().width); gex.p2slide.setMaximum(this.getSize().width); Graphics2D g2d = (Graphics2D) g; g2d.setPaint(gpaint); //setting context g2d.fill(new Rectangle2D.Double(0, 0, this.getSize().width, this.getSize().height)); g2d.setColor(Color.black); BasicStroke stroke = new BasicStroke(4); g2d.setStroke(stroke); Line2D line1 = new Line2D.Double(p1pos, 0, p1pos, this.getSize().height); g2d.draw(line1); Line2D line2 = new Line2D.Double(p2pos, 0, p2pos, this.getSize().height); g2d.draw(line2); // step two-set the graphics context } }
Figure 3.4 A cyclic GradientPaint object with moderate separation of P1 and P2.
Figure 3.5 A cyclic GradientPaint object with small separation of P1 and P2.
Figure 3.6 An acyclic GradientPaint object with small separation of P1 and P2.
Figure 3.7 An acyclic GradientPaint object with moderate separation of P1 and P2.
In Figure 3.4, the gradient of a GradientPaint is specified by two points, P1 and P2, together with the colors to use at each point. If a fifth argument, cyclic, is specified, the pattern is repeated outside of the points in cyclic fashion. If acyclic is specified, the full colors prevail in the zones outside the points.
NOTE
Because the GradientPaint is specified as acyclic, the gradient doesn't repeat past the two points.
Texture Paints
A texture can be specified for the Paint object. Textures will be explained in greater detail in both Chapter 4 and in Part III, "Visualization and Virtual Environments: The Java 3D API," where texture painting is used in the Virtual Shopping Mall example. For now, realize that you must create a BufferedImage object either from an external source or, alternatively, by programmatically filling a BufferedImage using some algorithm. The BufferedImage object is then used as an argument to the constructor of the TexturePaint object. In addition, a Rectangle2D object must be passed that specifies how the texture is replicated across the Component to be painted. The constructor for a TexturePaint object is as follows:
public TexturePaint(BufferedImage txtbuffer, Rectangle2D anchor);
One critical point to keep in mind when using the TexturePaint object is that the size of the BufferedImage should be kept relatively small because the BufferedImage is replicated to fill whatever graphics object is being painted. When the TexturePaint object is instantiated, an anchoring rectangle is specified in user space coordinates. This anchoring rectangle (with its associated BufferedImage) is copied in both x and y directions infinitely across the shape to be rendered.
Listing 3.5 demonstrates the use of a TexturePaint object. In this example, four slider bars are used to control the anchoring rectangle.
Listing 3.5 TexturePaintEx.java
class SliderListener implements ChangeListener { TextureEx tex; myCustomCanvas mc; public SliderListener(TextureEx tex, myCustomCanvas mc) { this.tex = tex; this.mc = mc; } public void stateChanged(ChangeEvent e) { int hanchor = tex.hanchor_slide.getValue(); int vanchor = tex.vanchor_slide.getValue(); int hsize = tex.hsize_slide.getValue(); int vsize = tex.vsize_slide.getValue(); mc.createPaint(hanchor,vanchor,hsize,vsize); }//End of stateChanged }//End of SliderListener class myCustomCanvas extends Canvas { private String texture = "texture.jpg"; private TexturePaint tpaint; private int texheight, texwidth; Rectangle imageRect; private int hanchor,vanchor,hsize,vsize; Image image; TextureEx tex; public myCustomCanvas(TextureEx tex) { this.tex = tex; this.setSize(800,600); image = this.getToolkit().getImage(texture); MediaTracker mt = new MediaTracker(this); mt.addImage(image, 0); try { mt.waitForID(0); } catch (Exception e) { System.out.println("exception while loading .."); } if (image.getHeight(this) == -1) { System.out.println("Could not load: " + texture); } else { System.out.println("Loaded: " + texture); } texheight = image.getHeight(this); texwidth = image.getWidth(this); //createPaint(0,0,30,30); this.setSize(800,600); } public void createPaint(int hanchor, int vanchor, int hsize, int vsize) { this.hanchor = hanchor; this.vanchor = vanchor; this.hsize = hsize; this.vsize = vsize; BufferedImage bi = new BufferedImage _(texwidth,texheight,BufferedImage.TYPE_INT_RGB); Graphics2D big = bi.createGraphics(); big.drawImage(image,0,0,this); RenderingHints interpHints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); big.setRenderingHints(interpHints); RenderingHints antialiasHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); big.setRenderingHints(antialiasHints); Font f1 = new Font("Helvetica", Font.BOLD, 24); big.setFont(f1); big.setColor(Color.black); big.drawString("VRSciences", 125,100); big.setColor(Color.white); Font f2 = new Font("Helvetica", Font.BOLD, 18); big.setFont(f2); big.drawString("Cognitive Neuroscience", 75, 120); big.drawString("meets", 160, 140); big.drawString("Virtual Reality",120, 160); big.drawString("http://www.vrsciences.com", 100, 180); imageRect = new Rectangle(hanchor,vanchor, hsize, vsize); tpaint = new TexturePaint(bi,imageRect); repaint(); } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { tex.hsize_slide.setMaximum(this.getSize().width); tex.vsize_slide.setMaximum(this.getSize().height); tex.hanchor_slide.setMaximum(hsize); tex.vanchor_slide.setMaximum(vsize); Graphics2D g2d = (Graphics2D) g; g2d.setPaint(tpaint); //setting context g2d.fill(new Rectangle2D.Float(0.0f, 0.0f, this.getSize().width, this.getSize().height)); } }
Figures 3.8, 3.9, and 3.10 show the effects of changing some of the setting in TexturePaintEx.java.
Figure 3.8 A screen from TexturePaintEx with settings for a large anchoring rectangle.
Figure 3.9 A screen from TexturePaintEx with settings for a moderately sized and shifted anchoring rectangle.
Figure 3.10 A screen from TexturePaintEx with settings for an extremely small anchoring rectangle.
Making a Custom Paint
Finally, in cases where the three standard Paint objects cannot be used to make the desired effect, you can create a custom paint. This can be fairly challenging. The problem becomes tenable, however, given a proper understanding of the Paint and PaintContext interfaces discussed previously. For expediency, the developer should consider at length the many ways in which transparency and composite overlay can be used with the preexisting Paint classes to accomplish a particular goal.
Creating a custom Paint object is a two-part process. The developer must write at least one implementation of the PaintContext interface and then write an implementation of the Paint interface that uses this custom PaintContext.
The most code intensive part is writing a custom implementation of the PaintContext interface. There are only three different methods in the PaintContext interface. They are as follows:
public void dispose(); ColorModel getColorModel(); Raster getRaster(int x, inty, int w, int h );
If you are familiar with the Java representation of an image (described in the introduction to this section and in far greater detail in the next chapter), it is clear that we have the makings of an image here. Specifically, there is a Raster and a ColorModel present. Remember that a Raster consists of data (the DataBuffer object) and the methods for interpreting that data (SampleModel).
When creating a custom implementation of PaintContext, it generally isn't necessary to modify the getColorModel() or dispose() methods. Most of the real work occurs in writing the getRaster() method. Overall, this work falls in the domain of image processing. The custom Paint is made by operating on the pixels in the Raster. An example of making a custom Paint object is given in the next chapter.
The last part of the procedure is to implement the custom Paint interface object. As already mentioned, there is only one method in the Paint interface, the createContext() method, who's sole purpose is to return a PaintContext whenever Paint is called. So, for example, if the PaintContext that was made is called myCustomPaintContext, implementing the createContext() method would look like the following:
public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform transform, RenderingHints hints) { try{ return new myCustoomPaintContext(args); }catch(NoninvertibleTransformException e){ e.printStackTrace(); throw new IllegalArgumentException(); } }