If the line flag is TRue, the user is drawing lines. To draw lines, Painter uses the Line2D.Double class. Because Line2D.Double is one of those rare Graphics2D objects that doesn't need to be passed only the upper-left point at which to begin drawing, you can draw the line simply by using the start and end points: if(line){ Line2D.Double drawLine = new Line2D.Double(start.x, start.y, end.x, end.y); . . . There's a graphics effect you have to take care of here as well: If the user has selected the Drop shadow graphics effect, you also have to draw the shadow. Shadows should not completely obscure what's underneath them; they should only be slightly darker. You can draw lines that work excellently as shadows using the Java2D Composite class. To draw a shadow, you can create a new Composite object and install it in the gImage graphics context. First, you save the current Composite object as well as the current Paint object (which specifies things such as drawing color and stroke thickness): if(shadow){ paint = gImage.getPaint(); composite = gImage.getComposite(); . . . Now you can change the drawing color temporarily to black and set the opacity with which the shadow will be drawn, using the AlphaComposite class: if(shadow){ paint = gImage.getPaint(); composite = gImage.getComposite(); gImage.setPaint(Color.black); gImage.setComposite(AlphaComposite.getInstance (AlphaComposite.SRC_OVER, 0.3f)); . . . In this case, the shadow is draw over any underlying image, with an opacity of .3 (if you want darker shadows, increase that value to .4 or .5). Using Java2D, you can create all kinds of drawing effects using the AlphaComposite class; you can see the significant fields, such as SRC_OVER, of this class in Table 4.3.
After the graphics object gImage has been primed for drawing shadows, all you have to do is to draw the line to the left and lower than the original line, restore the gImage context to its original settings, and then draw the original line itself (which will then lie on top of any shadow): Line2D.Double line2 = new Line2D.Double(start.x + 9, start.y + 9, end.x + 9, end.y + 9); gImage.draw(line2); gImage.setPaint(paint); gImage.setComposite(composite); } gImage.draw(drawLine); } . . . You can see an example in Figure 4.2, where the user is drawing some thick lines with drop shadows. Figure 4.2. Drawing some lines.That completes how Painter draws lines. What about ellipses? |