Chapter 4
Download
1 / 26

Chapter 4 - PowerPoint PPT Presentation


  • 229 Views
  • Updated On :

Chapter 4 Java 2D API Drawing Basics (review) Upper left corner is (0,0) Y-coordinate increases as move down from upper left X-coordinate increases as move to the right

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Chapter 4' - paul


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Chapter 4 l.jpg

Chapter 4

Java 2D API


Drawing basics review l.jpg
Drawing Basics (review)

  • Upper left corner is (0,0)

  • Y-coordinate increases as move down from upper left

  • X-coordinate increases as move to the right

  • A graphics context enables drawing on the screen.  The Graphics class manages a graphics context, controlling how information is drawn.  It includes methods for drawing, font manipulation, color manipulation etc.

  • Graphics is an abstract class.  This contributes to portability.  For each platform, a Graphics subclass implements the drawing capabilities.

  • Class Component is the superclass for many classes in java.awt. 

  • Method paint of class Component is called when the contents should be painted, such as when first displayed, when window is resized, etc. 

  • Method paint takes a Graphics reference as an argument (which allows a subclass to be passed in).  The actual reference is platform-specific. 

  • paint should not be called directly!  Drawing graphics is an event-driven process.  Should invoke method repaint of class Component.  This requests a call to method update as soon as possible, to clear the Component's  background.  Method update then calls paint. 


Basics continued l.jpg
Basics continued

  • Class JComponent is the superclass for many classes in javax.swing.  The Swing mechanism calls method paintComponent of class JComponent.  As above, the developer should call repaint.

  • Packages included in the Java 2D API:

    • java.awt.image – deal with jpg, gif etc.

    • java.awt.color – Grayscale and RGB

    • java.awt.font

    • java.awt.geom – 2D images like ellipse, line, point, etc.

    • java.awt.print – for printing

    • java.awt.image.renderable – allows images to be manipulated independent from rendering


Graphics 2d classes l.jpg
Graphics 2D Classes

Shape

Polygon RectangularShape Rectangle Line2D CubicCurve2D Area GeneralPath QuadCurve2D

Area methods:

add, subtract, intersect, exclusiveOr

Rectangle2D methods:

intersection, union

Rectangle2D RoundRectangle2D Arc2D Ellipse2D

  • Methods of Shape interface:

  • boolean contains(double x, double y)

  • boolean contains(double x, double y, double w, double h)

  • Rectangle getBounds()

  • PathIterator getPathIterator(AffineTranform at)

  • boolean intersects(double x, double y, double w, double h)


Graphics2d l.jpg
Graphics2D

  • Class java.awt.Graphics2D enables drawing.  Need to cast the Graphics reference passed to paint to a Graphics2D.

  • Java 2D can render three types of graphics primitives: images, text and geometrical shapes.

  • Seven Graphics2D state attributes determine how graphics primitives are rendered: 

    • clipping - defines the area in which rendering operations take effect.  Can be any geometrical shape.

    • compositing - a set of blending rules that control how the pixels in a source image mix with the pixels in a destination image.

    • font - text is rendered by drawing and filling glyphs.

    • paint - determines colors, patterns, gradients for filling and outlining a shape.

    • rendering hints - techniques can be specified to help optimize drawing.

    • stroke - determines the outline of the shape to be drawn.

    • transforms - ways to perform linear transformations.


Graphics2d continued l.jpg
Graphics2D - continued

  • Interface Paint determines the color of a shape that is drawn.  It can be a predefined Color, a GradientPaint, SystemColor or TexturePaint.

  • GradientPaint takes 7 arguments: starting coordinate, starting Color, ending coordinate, ending Color, and whether it's cyclic (true) or acyclic (false).   The two coordinates determine the direction of the gradient.

  • Method fill draws a filled shape. 


Graphics2d continued7 l.jpg
Graphics2D - continued

  • Interface Stroke provides options for the outline of a shape.  BasicStroke provides constructors to set the line width, specify how the line ends (end caps: CAP_BUTT, CAP_ROUND, CAP_SQUARE), how lines join together (line joins: JOIN_BEVEL, JOIN_MITER, JOIN_ROUND) and optional dash attributes (determined by array of lengths)


Graphics2d continued8 l.jpg
Graphics2D - continued

  • A BufferedImage describes an Image with an accessible buffer of image data.  It is comprised of a ColorModel and a Raster of image data. The first two parameters are the width and height in pixels, the third parameter determines whether the image will be in color or gray scale.  createGraphics creates a graphics2D that can be used for drawing on the BufferedImage (e.g., with fillRect, etc.).


Graphics2d continued9 l.jpg
Graphics2D - continued

  • The TexturePaint object uses the image stored in its BufferedImage as the fill texture for a shape.  The second argument is the area from the BufferedImage that will be replicated. 

  • Many shapes (such as Arc2D.Double) are drawn within a bounding rectangle.  Arc2D is determined by: upper left, upper right, width, height, start angle in degrees, arc angle and a closing option (Arc2D.PIE, Arc2D.CHORD and Arc2D.OPEN).


Graphics2d continued10 l.jpg
Graphics2D - continued

  • Shapes.java output:

Rectangle2D

Arc2D

Gradient

Lines (Strokes)

BufferedImage


Transformations l.jpg
Transformations

  • Not covered in our text

  • AffineTransform can be applied to an individual shape or can be set for a graphics context and applied to all shapes.

  • Allows you to rotate, translate, shear, and scale. createInverse can be used to get a transform to undo the transformation.


Graphics 2d continued l.jpg
Graphics 2D - continued

  • Graphics2D extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout.

  • Coordinates passed to a Graphics2D object are specified in device-independent coordinate system called User Space.  By default, when drawing to a screen or image, user space is the same as device space.

  • The Graphics2D contains methods that allow you to modify the coordinate system. For example, translate moves the origin of the coordinate system.

  • Every Graphics2D object is associated with a target that defines where rendering takes place. A GraphicsConfiguration object defines the characteristics of the rendering target, such as pixel format and resolution. The same rendering target is used throughout the life of a Graphics2D object.

  • The Rendering Process can be broken down into four phases that are controlled by the Graphics2D rendering attributes. The renderer can optimize many of these steps, either by caching the results for future calls, by collapsing multiple virtual steps into a single operation, or by recognizing various attributes as common simple cases that can be eliminated by modifying other parts of the operation.


Graphics 2d continued13 l.jpg
Graphics 2D - continued

  • The steps are:

    • Determine what to render.

    • Constrain the rendering operation to the current Clip.

      • The Clip is specified by a Shape in user space and is controlled by the program using the various clip manipulation methods of Graphics and Graphics2D.

      • This user clip is transformed into device space by the current Transform and combined with the device clip, which is defined by the visibility of windows and device extents.

      • The combination of the user clip and device clip defines the composite clip, which determines the final clipping region. The user clip is not modified by the rendering system to reflect the resulting composite clip.

    • Determine what colors to render.

    • Apply the colors to the destination drawing surface using the current Composite attribute in the Graphics2D context.


Graphics2d continued14 l.jpg
Graphics2D - continued

  • Class GeneralPath represents a shape constructed from lines and complex curves.

  • The x- and y-coordinates are represented by two int arrays.

  • The moveTo method specifies the first point (could be first two points in arrays, or could be shifted).

  • The lineTo method draws a line to the next point in the star.

  • The closePath method draws a line from the last point to the target of moveTo.

  • The translate method moves the drawing origin.

  • The rotate method rotates around an origin.


Graphics2d continued15 l.jpg
Graphics2D - continued

  • Shapes2.java output:


Exercises l.jpg
Exercises

  • Update shapes to make figure

  • Update shapes2 to display 4 triangles, change center


Image processing l.jpg
Image Processing

  • Image processing is the manipulation of digital images by applying filters - mathematical operations that change images.

  • Java 2D API shields developers from underlying mathematics

  • Compression filters reduce a digital image's memory usage, for reduced storage size and faster transmission.  Used in HDTV, video phones and virtual reality.

  • Measurement filters collect data from digital images.  They are used in image recognition and machine vision (e.g., for use with robots).

  • Enhancement filters alter certain physical aspects of an image, often to restore corrupted images.  They can remove noise, sharpen edges and brighten colors. 


Image processing18 l.jpg
Image Processing

  • Filters operate on BufferedImage objects.  Contains a Raster and a ColorModel. 

  • A Raster is composed of a DataBuffer and a SampleModel.  The DataBuffer stores the raw data for an image.  The SampleModel organizes the data that determines a pixel's color components.  Each pixel is composed of samples, which are number values that represent the pixel's color components. 

  • The SampleModel accesses the sample values in the DataBuffer for any given pixel. 

  • The ColorModel is an interpreter for the Raster, converting the sample values for each pixel to the appropriate color. 

  • The ColorModel's operation depends on the color scale of the image.  Two common color scales are grayscale and RGB.

  • TYPE_INT_RGB uses three 8-bit segments to represent red, green and blue color components.

  • Method createGraphics creates a Graphics2D, which can be used to draw into this BufferedImage.


Background l.jpg
Background

*e.g., RGB has 3 “bands” per image; one band has all red, one has all blue, one has all red. 2 options: all samples from a particular band can be stored contiguously or all samples from a single pixel can be stored contiguously.

Raster – rectangular array of pixels

encapsulates dataBuffer (stores

image data)

sampleMode (describes how pixels

are stored in dataBuffer) *

Ex:SinglePixelPackedSampleModel;

bitmasks [0]=16711680, [1]=65280, [2]=255; bitSizes = 8

Raster includes height, width,

minX, minY (bounding rectangle)

numBands*,

numDataElements (per pixel)


Background cont l.jpg
Background – cont.

image

colorModel

Raster

alphaMask, blueMask, greenMask, redMask (nBits, maskOffsets etc.)

is_sRGB

colorSpace (type, minVal, maxVal, etc.)



Image processing application l.jpg
Image Processing - application

  • Deitel example creates interface Java2DImageFilter with just one method, processImage.

  • processImage is used to deliver data from an ImageProducer to an ImageConsumer.

  • Create subclasses that implement various filters


Image processing application23 l.jpg
Image Processing - application

  • MediaTracker is a utility class to track the status of a number of media objects. Currently only images are supported.

  • Use addImage to add an image.  Image can have a unique id that controls the priority order that images are fetched. 

  • Constructor takes a reference to the component (e.g., a JPanel) using the tracker's services. 

  • After images have been added, use waitForAll to start loading all images.  Could do waitForID with a parameter to wait for a particular image to load.


Image processing application24 l.jpg
Image Processing - application

  • Toolkit is the abstract superclass of all actual implementations of the Abstract Window Toolkit. Subclasses of Toolkit are used to bind the various components to particular native toolkit implementations.  Includes methods to create various components, such as buttons, checkboxes, images etc.

  • createImage creates an image which decodes the image stored in the specified byte array.

  • The data must be in some image format, such as GIF or JPEG, that is supported by this toolkit.

  • The ImagePanel creates an image via the call:

    Toolkit.getDefaultToolkit().createImage( imageURL );


Imageobserver l.jpg
ImageObserver

  • Images may take awhile to load

  • An object can register itself as an imageObserver and do a call such as getWidth.

  • getWidth can be asynchronous. Will return the value once the file is loaded.

  • Can also use null for ImageObserver parameter, indicating image is already loaded (that’s done in Java2DExample).


Exercise l.jpg
Exercise

Sepia details:

// tint shadows darker

if (red < 60) {

red *= 0.9;

green *= 0.9;

blue *= 0.9;

} else if (red < 190)

// tint midtones light brown by

// reducing the blue

blue *= 0.8;

else

// tint highlights a light yellow

// by reducing the blue

blue *= 0.9;

Use BufferedImage methods such as getRaster, getData, getCompatibleWritableRaster etc. to access pixels. getWidth, getHeight of image for loop indices.

  • Update Java2DExample to include:

    • Sepia

    • Grayscale (ColorConvertOp)

    • Light Grayscale (RescaleOp, ColorConvertOp)

    • Emboss (ConvolveOp)

    • Flip Vertical (AffineTransform)

    • Flip Horizontal (AffineTransform)