EARTH WEEK
Go paperless and save 40% on eligible eBooks, 70% on video now through April 26. Shop the sale.
Register your product to gain access to bonus material or receive a coupon.
1426F-1
Awesome graphics with the Java 2D API--step by step!
Sophisticated graphics are crucial to a wide range of applications. Now you can create awesome graphics using Java technology without the expense and hassle of platform-specific development. Sun Microsystems Java technology architect Vincent Hardy shows you how-in full-color! From text manipulation to geometry rendering, compositions and image manipulation, you'll see exactly what can be done-and learn how to do it, step-by-step with detailed code examples.
Java 2D API Graphics offers an in-depth overview of the Java 2D API, its architecture, features, components and possibleapplications. It also introduces Hardy's exclusive Graphic Layers Framework-a high-level programming model that dramatically simplifies programming with the Java 2D API (included free on the accompanying CD-ROM).
Key topics covered include:
Click here for a sample chapter for this book: 0130142662.pdf
(NOTE: Most chapters conclude with a Conclusion.)
I. JAVA 2D API OVERVIEW.
1. The Java 2D API Rendering Model.The Java 2D API Rendering Model. The Java 2D API Features. Output Device Independence. Renderable Graphic Objects. Graphic Context Attributes.
2. Java 2D API Overview.Acquiring a Graphics2D Object. Coordinate Spaces. * User Space. * Device Space. * Reconciling User Space and Device Space. Graphic Objects and Rendering Methods. Rendering Shapes. Rendering Text. * Simple Text Rendering. * Styled Text Rendering. * Advanced Text Manipulation. * Custom Glyph Layouts. Rendering Images. * Bufferedimage. * Creating a Bufferedimage and Loading Images. * Filtering Images. Graphic Context Attributes.
3. Rendering to an Output Device: Screen, Printer, and Images.Drawing to the Screen. Drawing to the Printer. Rendering to an Offscreen Buffer. Resolution Independence.
4. Manipulating and Rendering Shapes, Images, and Text.Shapes. Different Uses of Shape. * Creating an Arbitrary Shape. * Drawing Shapes. * Filling Shapes. * Transforming Shapes. * Clipping. * Hit Detection. Different Types of Shapes. Summary. Rendering Images: Bufferedimages. Rendering a Bufferedimage. Bufferedimage Internals. * Concerns Addressed By Bufferedimage. * Databuffer. * Samplemodel. * Colormodels. * Colorspace. * Putting It All Together Again. * Saving a JPEG File in CMYK. Bufferedimageop. * Affinetransformop. * Colorconvertop. * Convolveop. * Rescaleop. * Lookupop. * Bandcombineop. Summary. Text Manipulation. Attributedstring. A Closer Look At Textattribute. * Font Definition Attributes. * Text Layout Control. * Rendering Control. Advanced Text Rendering with Textlayout and Linebreakmeasurer. * International Text Complexities. * Text Editing Features. * Text Rendering Support. * Creating and Using an Attributedstring. * Creating a Text Paragraph. Custom Glyph Layouts. * Creating a Glyphvector. * Processing the Largest Glyph Width. * Custom Glyph Layout. * Rendering a Glyphvector.
5. Graphic Context Attributes.Affinetransform. A Formal Definition of Affinetransform. Types of Elementary Transforms. * Scale. * Rotation. * Shear. * Translation. * Reflection. Composing Affinetransforms. * Transform Composition Defined: Transform Stack. * Composition Order. * Composing For More Intuitive Effects. Summary. Strokes. The Stroke Interface. The Basicstroke Implementation. * Stroke Size. * End Caps. * Line Joins. * Dashing Patterns. * Miter Limit. Summary. Paints. What Kinds of Paints Are There? * Color. * Gradientpaint. * TexturePaint. Advantage of the Paint Interface. Features of the Paint Interface. * The Paintcontext Interface. Summary. Font. What Are Fonts? Available Fonts. Using Fonts. Creating Fonts. * Font Name. * Font Size. * Font Weight. * Font Posture. * Fonttransform. * Font Constructors. * Deriving Fonts. Font Metrics. * Vertical Metrics. * Horizontal Metrics. * Accessing Font Metrics. Summary. Composite. What Is Compositing? Where Is Compositing Used? Alphacomposite Rules. * Creating an Alphacomposite. * Visual Representation of Alphacomposite Rules. Composite Internals. * The Composite Interface. * The Compositecontext Interface. Summary. Renderinghints. Why Renderinghints? * Platform Rendering Capabilities. * Programmer's Rendering Ideal. * Reconciling Capabilities and Options. Where and How Are Renderinghints Used? * Graphics2D. * Paint and Composite. * Bufferedimageop. Available Renderinghints. * Pixel Interpolation. * Alpha Interpolation. * antialiasing. * Color Rendering. * Dithering. * Fractional Metrics. * Rendering. Summary. Clipping. Defining the Clipping Area. Summary. Parting Thoughts. End of Part I.
II. THE GRAPHIC LAYERS FRAMEWORK.
6. The Graphic Layers Framework Fundamentals.Purpose of the Graphic Layers Framework. Overview of the GLF Packages. The “Hello Layers” Example. Step. Defining the Layer Stack. Step. Creating a Compositionfactory and Defining Its Option Set. * Creating a Compositionfactory. * Defining the Compositionfactory Option Set. Step. Implementing the Compositionfactory: Creating and Stacking Layers. * Creating a Layer Stack. * Background Layer. * Text Layer. * Shadow Layer. * Stacking Layers. Viewing the Hello Layers Composition. Modifying and Experimenting with Control Properties.
7. The GLF Core: Working with Layers.Introduction: Graphical Compositions. The Composition Interface. Layers and Layercompositions. The Layer Abstract Class. Using Layercompositions. The Layercomposition Operation (Advanced Topic). * Backgroundpaint. * Renderinghints. * The Paint Process. * Offscreen Layer Rendering. * Layer Filtering. Bufferedimageop Vs Rasterop. * Filter Margins. * Layer Masking. * Finishing the Paint Process. Position. Anchoring Objects. Adjusting Positions about the anchor. Applying Transforms about an Object's Center. Shapelayer. Shapelayer Operation: Placing Shapes and Using Renderers. Fillrenderer. Strokerenderer. Compositerenderer. Setting Shapelayer Mementos. Textlayer. Operation. Maketextblock (Advanced Topic). * Breaking Lines Into Paragraphs. * Turning Text Into a Shape. Imagelayer. Imagelayer Operation. Positioning Images in a Layercomposition. Compositionproxylayer. Compositionproxylayer Operation. Reusing Compositions with Compositionproxylayer. One Last Example.
8. The GLF Studio and Utilities: Experimenting with Layers.Introduction. Viewing Compositions. Supporting Classes. * Compositioncomponent. * Compositionframe. Utilities That Display Compositions. * Compositionviewer. * Compositionshow. * Compositionstudio. Saving Compositions. Serializing Composition Configurations. * What Is Serialization? * Serializing Compositionfactories. Text-Based Serialization. Saving Compositions as Images. Configuring Compositions. Loading a Compositionfactory. * Loading a Compositionfactory as a Java Bean. * Loading a Compositionfactory as a File. Configuring a Composition. * Mapping Property Names to UI Label Name. * Supported Property Types and Related User-Interface Controls. * Configuring a Font Property. * Configuring a Glyph Property. * Configuring a Color Property. * Configuring a File. Previewing a Compositionfactory Configuration. Saving a Compositionfactory Configuration. Afterword about Loading Images.
9. The GLF Goodies: Taking Advantage of Java 2D's Extensible Design.Introduction. Custom Paints. Creating a Custom Paint Implementation (Advanced Topic). * Writing an Implementation of the Paintcontext Interface. * Writing an Implementation of the Paint Interface. Gradientpaintext. Radialgradientpaint. Radialgradientpaintext. Custom Strokes. Compositestroke. Controlstroke. Shapestroke. Wavestroke. Textstroke. Custom Composite. Creating a Custom Composite Implementation (Advanced Topic). * Writing an Implementation of the Compositecontext Interface. * Writing a Composite Implementation. Colorcomposite: Combining HSB Values. * Colorcomposite Defined. * Using Colorcomposite. * About the Colorcomposite Implementation. Custom Bufferedimageops and Rasterops. The Bufferedimageop and Rasterop Interfaces. * Hints. * Spatial Information. * Creating a Compatible Destination. * Filtering. Implementing a Custom Filter (Advanced Topic). * Bufferedimageop or Rasterop. * Hints. * Spatial Characteristics. * Supported Formats. * Implementation. Lightop. * Operation/Design. * Adding Lights to a Litsurface. The Toneadjustmentop Filter. The Compositeop and Compositerasterop Filters. Nonlinear Transformations. Transform and Abstracttransform. Wavetransform. Bumptransform. Nonlinear Transforms Approximations. End of Part II.
III. RENDERING EFFECTS.
10. Introduction.How to Read This Part. Format Technical Content. Rendering Effects Index. More Rendering Effects: the Gallery. Important Note on Performance.
11. Creating Realistic Shadows.Creating a Drop Shadow. Shadow Basics. * Creating a Sense of Light and Depth. * Creating a Realistic Shadow. The Image Shadow Layer Stack. Getting the Raw Material. * Loading an Image and Its Mask. * Creating and Transforming the Composition Label. Computing the Composition Size. Creating the Composition Layers. * The Label Layer. * The Label Shadow Layer. * The Tinted Image Layer. * The Image Shadow Layer. * Stacking Up Layers. Creating a Cast Shadow. Layer Stack Description. Getting the Raw Material. * Creating the Wavy Label. * Creating the Cookie-Cutter Cut Ellipse. Computing the Composition Size. Creating the Composition Layers. * Label Layer. * Label Shadow Layer. * Symbol Cast Shadow. * Embossed Symbol Layer. * Stacking Up Layers. Creating a Recessed Shadow. Layer Stack Description. Getting the Raw Material. Computing the Composition Size. Creating the Layers. * Label Layer. * Label Shadow Layer. * Dark Rim and Light Rim. * Stacking Up Layers. Putting It All Together. Loading a Compositionfactory Bean. Configuring and Building a Compositionfactory Object. Using Compositionproxylayer.
12. Making Text Stand Out.Creating a Simple Glow. Layer Stack. Getting the Raw Material. Computing the Layer Size. Creating the Composition Layers. * Text Glow Layer. * Text Layer. * Image Glow. * Image Layer. * Stacking Up Layers. Creating a Sophisticated Glow. Creating a More Sophisticated Glow. Creating a Background Texture with Shapes.
13. Sculpting with Light.The Layer Stack. Getting the Raw Material. Computing the Composition Size. Embossing with Spotlight. Using Lightop For Embossing. * Creating a Spotlight. * Creating a Texture Map. * Creating a Litsurface. * Creating a Lightop Filter. Attaching Lightop to a Shapelayer. Carving with Spotlight. Extruding with Spotlight. Increasing Legibility. Adding a Dark Glow Under the Embossed Text. Adjusting the Carved Text's Color. Painting the Top of the Extruded Text. Stacking Up Layers.
14. Fancy Text Layouts.Creating a Circular Text Layout. Layer Stack. Circular Text Layout. * Laying Out Text. * Creating a Layer. Creating a Triangular Text Layout. Making Symbol Tags Legible and Attractive. Layer Stack. Getting the Raw Material and Computing the Composition Size. Background Glyph Layer. Stroking with Multiple Pen Width. Putting It All Together Again.
15. Tinting Photographs.Layer Stack. Getting the Raw Material. Computing the Composition Size. Creating the Composition Layers. Antiquing a Photograph with Fuzzy Edges. Fast Blur to Create a Border Effect. Making Text Legible Again.
16. Creating a Sense of Volume.Creating a Sphere. Creating the Proper Radial Gradient Paint. * Positioning the Radial Gradient Paint Control Circle. * Choosing the Right Gradient Colors. Using Radialgradientpaintext Creatively. * Creating the Sphere. * Creating the Sphere Shadow. Creating a Cylinder. Getting the Raw Material: Creating the Cylinder Shapes. Building the Cylinder Body and Top. Creating the Shadow. Creating a Bar. Creating the Base Rectangular Shapes. Rendering the Bar Face. Creating the Bar Side Layer. Creating the Bar Top. Creating the Shadow. Putting It All Together Again. Layer Stack. Getting the Raw Material. Creating the Composition Layers. * Sky and Sea. * Sun and Sun Rays. * Stroking with Text. Grouping Compositions in a Single Layer.
17. Gallery.Brushed Metal. Recessed Shadow. Shadow Stand-Out. GLF Logo. Gradient Waves. Text Flowers. Soft Focus. Sunset. Shape Texture. Lookup Pattern. Lights. Bibliography.
Bibliography.The Java 2D API provides the underlying support for graphics in the Java platform (see Figure P.1). Other APIs that need graphic support, such as the Abstract Window Toolkit (AWT) or Swing, rely on the Java 2D API for all drawing operations.
Figure P.1
The Java 2D API in the Java platform
The Java 2D API became available to programmers in its beta form during the second half of 1997 when the first early-access releases of the Java 2 platform (JDK 1.2) became available. The specification had been out for some time before that, and I (although not working ar Sun at the time), along with many, had great expectations. Why?
If you had a look at the specification back then, you soon realized that Java graphics were about to change dramatically. The announced feature set was impressive:
Expectations ran high, and when the API finally became available, many programmers started using all these promising features. Anybody who went through this experience soon noticed a number of key points about the Java 2D API.
The Java 2D API delivers a wealth of features, but it may not be obvious how they can or should be used. Actually, it depends on the type of application; the way features are used or the reason for which they are used depends on whether you are, for example, writing a satellite image processing program or a web animation.
This book looks at how the Java 2D API features can be used, combined, and extended.
When we say the API is feature rich, we really mean that there has been a huge feature improvement from earlier versions of the JDK. To use a musical analogy, earlier versions of the Java platform provided a flute. The Java 2D API gives us an orchestra. With a flute, a music score is useful to play the proper sounds. This is even more true for a symphonic orchestra: guidance is needed to have all the instruments and musicians play in harmony and produce a pleasing result. The goal of this book is to provide guidance so that programmers can write beautiful partitions with the Java 2D API.
For example, the images in Table P.1 are completely created with the Java 2D API and the Graphic Layers Framework (GLF) provided in this book. These examples show the type of visual output the Java 2D API can create; this book explains how to obtain this type of result and provides all the related software.
Table P.1
Example Rendering Effects; Examples from Part III
We said this book explains how to use, combine, and extend the Java 2D API features. The book structure reflects this purpose; it has three parts.
Part I contains a detailed overview of the Java 2D API. It starts with an introduction to the API rendering model (Chapter 1) and a summary of its features (Chapter 2). Chapters 3, 4, and 5 study the different parts of the API in greater detail.
Part II introduces the Graphic Layers Framework (GLF) that builds on the Java 2D API and provides a higher-level programming model to create and compose rendering effects. I developed the Graphic Layers Framework for this book: it provides an advanced example of how the Java 2D API can be used and extended. GLF contains the following:
The different GLF packages are the foundation for the rendering effects in Part III. That part is about combining features; it demonstrates how sophisticated the graphics support of the Java platform now is. This part shows how to create effects such as shadowing, lighting, and carving. The final chapter of Part III contains a gallery of images that further illustrates the sophistication of the Java 2D API and shows GLF at work.
This book can be read in different ways. It can be read linearly, from start to end. This is the recommended way if you are not familiar with the Java 2D API or with computer graphics. This approach will give you an in-depth understanding of the Java 2D API and how this book uses it to create rendering effects.
However, you might decide that you are not interested in the inner workings of the Java 2D API or of the Graphic Layers Framework. In that case, you can start with Part II directly; Chapters 6 and 8 provide enough information about GLF to enable you to use it with no need to understand its implementation or the underlying Java 2D concepts. You will learn how to use the GLF capabilities to create rendering effects. The "Hello Layers" example (Chapter 6) can get you started with GLF quickly. You can then proceed to Part III and start experimenting with advanced rendering effects. If you choose that route, you will likely need to refer back to Parts I and II, where you will find explanations for issues that might seem obscure.
No matter how you read this book, you will find that it contains many code samples (there are about ninety examples, in addition to the Graphic Layers Framework itself). We usually chose to first show the code and then to explain it. This approach gives you a chance to read the code in its entirety first and then to read explanations. So, don't be discouraged if some point seems difficult while you are reading the code: it usually is the point that the following explanation details.
The CD-ROM that comes with this book contains two files:
Please refer to the readme file for instructions on how to install the Graphic Layers Framework and the book code examples on your computer.
Throughout the book, you will see code examples and references to the source code on the CD-ROM. For example, on page 238, you can see that the code example is AnchorPlacementTransform.java. We use the name of the corresponding class to refer to the example name, for example, AnchorPlacementTransform
.
There are two ways to run the examples provided in this book. One way is to use a tool with a user interface. The other one is to use a script. The former lets you browse through the book's examples. The latter lets you run a specific code example directly.
At the command prompt, type:
cd <installDir>demorunner
Figure P.2
demorunner startup window
This last commands summons a window, as shown in Figure P.2. The window contains folders for each part of the book. Each folder can be expanded into the different chapter folders, and each chapter folder can in turn be expanded to show its code samples, as illustrated in Figure P.3.
Figure P.3
Expanding demorunner's code example tree
Double-click on an example name to start it. The status bar, at the bottom of the window, shows a message reading Starting <ExampleName> in separate VM. Please wait. For example, in Figure P.4, we double-clicked on the AnchorPlacementTransform example. The example starts after a couple of seconds.
Figure P.4
Starting an example with demorunner
An alternate way to run a specific example directly is to use the runsnippet script. At the command line, type the following:
cd <installDir>runsnippet <exampleName>
For example:
runsnippet AnchorPlacementTransform