Home > Articles

This chapter is from the book

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();
  }
 }

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020