Lecture07 Graphics Programming in Java. Introduction Most of the graphics programming of java is...

25
Lecture07 Lecture07 Graphics Programming in Graphics Programming in Java Java
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    231
  • download

    1

Transcript of Lecture07 Graphics Programming in Java. Introduction Most of the graphics programming of java is...

Lecture07Lecture07

Graphics Programming in JavaGraphics Programming in Java

IntroductionIntroduction Most of the graphics programming of java Most of the graphics programming of java

is done with:is done with:• Java AWTJava AWT - - The Abstract Window Toolkit (AWT) The Abstract Window Toolkit (AWT)

supports Graphical User Interface (GUI) supports Graphical User Interface (GUI) programming. This is the very first GUI support programming. This is the very first GUI support Java had.Java had.

• SwingSwing – An advanced GUI library designed to – An advanced GUI library designed to overcome limitations of AWT.overcome limitations of AWT.

• Java2DJava2D - - The Java 2DTM API is a set of classes The Java 2DTM API is a set of classes for advanced 2D graphics and imaging. It for advanced 2D graphics and imaging. It encompasses line art, text, and images in a encompasses line art, text, and images in a single comprehensive model. These classes are single comprehensive model. These classes are provided as additions to the java.awt and provided as additions to the java.awt and java.awt.image packages. java.awt.image packages.

The Java 2D API Enhances the graphics, text, and imaging

capabilities of the Abstract Windowing Toolkit (AWT), enabling the development of richer user interfaces and new types of Java applications.

The Java 2D API supports enhanced colour definition and composition.

It provides a uniform rendering model for printers and display devices.

When used in conjunction with the Java Media Framework and other Java Media APIs, the Java 2D APIs can be used to create and display animations and other multimedia presentations.

Coordinate Systems

The Java 2D API maintains two coordinate systems:• User space is a device-independent, logical

coordinate system. Applications use this coordinate system exclusively; all geometries passed into Java 2D rendering routines are specified in user space.

• Device space is a device-dependent coordinate system that varies according to the target rendering device.

User Space The user space origin is located in the upper-left

corner of the space, with x values increasing to the right and y values increasing downward.

User space represents a uniform abstraction of all possible device coordinate systems.

The device space for a particular device might have the same origin and direction as user space, or it might be different.

User space coordinates are automatically transformed into the appropriate device space when a graphic object is rendered. Often, the underlying platform device drivers are used to perform this conversion.

Device Space The Java 2D API defines three levels of

configuration information that are maintained to support the conversion from user space to device space. This information is encapsulated by three classes:• GraphicsEnvironment : The GraphicsEnvironment

describes the collection of rendering devices visible to a Java application on a particular platform.

• GraphicsDevice : A GraphicsDevice describes an application-visible rendering device, such as a screen or printer.

• GraphicsConfiguration : Each possible configuration of the device is represented by a GraphicsConfiguration. E.g. 640x480x16 colours, 640x480x256 colours, etc.

A GraphicsEnvironment can contain one or more GraphicsDevices; in turn, each GraphicsDevice can have one or more GraphicsConfigurations.

Example – Graphics EnvironmentExample – Graphics Environment

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

GraphicsDevice[] gs = ge.getScreenDevices();for (int j = 0; j < gs.length; j++) {

GraphicsConfiguration[] gc = gs[i].getConfigurations();// Display the details of gcfor (int i=0; i < gc.length; i++) {

Rectangle virtualBounds = new Rectangle();virtualBounds = gc[i].getBounds();// Display details of virtualBounds

}}

Rendering with Graphics and Graphics2D

There is a three-step recipe for writing a graphics program in Java.

1. Get a graphics context.2. Set or Modify the context.3. Render something.

Graphics to Graphics2D

The graphics context of a awt program can be obtained as follows:public void paint(Graphics g) {

Graphics2D g2d = (Graphics2D) g;}

The casting is done to access the increased functionality of Graphics2D class which was made available via Java2D API.

ExampleExamplepublic void paint(Graphics g) {

// Cast the Graphics object to access the increased// functionality of Java2DGraphics2D g2d = (Graphics2D) g;// Set or Modify the graphics contextg2d.setColor(Color.red);// Render somethingg2d.fill(new Rectangle2D.Float(200.0f,200.0f,75.0f,75.0f));

}

Graphics Context The collection of state attributes

associated with a Graphics2D is referred to as the Graphics2D context.

Graphics context specifies properties of rendering.

You can modify the state attributes that form the Graphics2D context to:• Vary the stroke width.• Change how strokes are joined together.• Set a clipping path to limit the area that is

rendered.• Translate, rotate, scale, or shear objects when

they are rendered.• Define colours and patterns to fill shapes with.

Exercise

Check out the Java 2 SDK documentation and find out which of following are interfaces and which are classes: • Composite, CompositeContext, Paint,

PaintContext, Stroke, AffineTransform, AlphaComposite, BasicStroke, Color, GradientPaint, Graphics2D, TexturePaint.

Rendering on Components

Any object derived from the Component class has a Graphics object that can be used to render graphics onto it. • Thus the developer can render graphics

on all types of buttons, canvases, and check boxes.

An example rendering on a JButton:class myCustomButton extends JButton {

public void paint(Graphics g) {// Step one: Cast the Graphics object as Graphics2DGraphics2D g2d = (Graphics2D) g;// make the GradientPaint object going from blue to green// across from top left to bottom rightGradientPaint gp = new GradientPaint(0,0,Color.blue,

this.getSize().width/20,this.getSize().height/20,Color.green, true);

// Step two: set the graphics contextg2d.setPaint(gp);// Render somethingg2d.fill(new Rectangle2D.Float(0.0f,0.0f,75.0f,75.0f));}

}

Shape Primitives The shape primitives are all contained in the java.awt.geom

package. All shape primitives implement the PathIterator interface that specifies the outline of the shape.

Rectangle2D, RoundRectangle2D, Arc2D, and Ellipse2D are derived from the abstract class RectagularShape based on the common ability to describe these primitives through a rectagular bounding box.

Line, QuadCurve2D, and CubicCurve2D are line segments described by their two endpoints with the requisite control points.

GeneralPath allows for the specification of a series of points that can be connected with any combination of straight, cubic, or quadratic line segments.

Area allows the creation of new shapes through the use of intersection, union, and subtraction of other shapes.

Examplepublic void paint(Graphics g) {

Graphics2D g2d = (Graphics2D) g; // cast the graphics objectg2d.setColor(Color.green); // set the graphics context// Create some graphics - (A path)GeneralPath gp = new GeneralPath();int cwidth = this.getSize().width;int cheight = this.getSize().height;gp.moveTo((int) cwidth/2, (int) cheight/2); // starting pointgp.append(new Rectangle2D.Float((float)cwidth/2,

(float)cheight/2,20.0f,45.0f),true); // append a rectanglegp.lineTo((int)cwidth/4, (int)cheight/4); // line segmentgp.append(new Ellipse2D.Float((float)0.9*cwidth,

(float)0.25*cheight,20.0f,45.0f),true); // append a ellipsegp.closePath();g2d.draw(gp); // Render the graphicsreportGP(gp);

}

Example Example // Report about each segment as we go along the general pathpublic void reportGP(GeneralPath gp) {

AffineTransform at = new AffineTransform();PathIterator pi = gp.getPathIterator(at); int segNumber = 0;while (pi.isDone() == false) { segNumber++; System.out.println("Getting data for segment#: "+ segNumber

+"**"); float[] coords = new float[6]; // get segment types and sequential pairs of (x,y) coords System.out.println("Current Segment Type: "+

pi.currentSegment(coords)); // print coords pairs

for(int j=0;j<6;j++) System.out.println("j:"+j+" coords[j] "+coords[j]);

pi.next();}

}

Graphics Stroking Stroking a Shape such as a

GeneralPath object is equivalent to running a logical pen along the segments of the GeneralPath. • The Graphics2D Stroke attribute defines

the characteristics of the mark drawn by the pen.

• A BasicStroke object is used to define the stroke attributes for a Graphics2D context.

Example code segmentpublic void paint(Graphics g) {

Graphics2D g2d = (Graphics2D) g;// Create some graphicsGeneralPath gp = new GeneralPath();// build gpBasicStroke stroke = new BasicStroke(10);

// set line thickness to 10// modify graphics context - change the strokeg2d.setStroke(stroke);g2d.draw(gp); // render graphics

}

Fill Attributes and Painting The fill attribute in the Graphics2D context is

represented by a Paint object. You add a Paint to the Graphics2D context by

calling setPaint. There are three classes that implement Paint

interface• Solid color painting with the Color object.• Gradient painting with the GrdientPaint object.• Texture painting with the TexturePaint object.

When a Shape or glyph is drawn (Graphics2D.draw, Graphics2D.drawString), the Paint is applied to all of the pixels that lie inside of the Shape that represents the object’s stroked outline.

When a Shape is filled (Graphics2D.fill), the Paint is applied to all of the pixels that lie within the Shape’s contour.

Solid Color Painting

To user-define predefined color objectsColor red = new Color.red;

To specify RGB values between 0 and 1 Color red = new Color(1.0f,0.0f,0.0f);

To specify an alpha value for transparency

Color red = new Color(1.0f,0.0f,0.0f,0.5f);

Gradient Painting GradientPaint object represent transition

between two colors. In order to create a GradientPaint object it is necessary to specify:• The starting and end points for the transition.• The two colors to use.• An optional rule to specify how the paint looks

outside the region specified by the starting and end points.

This 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).

An Example: Gradient Paintingpublic void paint(Graphics g) {

Graphics2D g2d = (Graphics2D) g;// ...int width = this.getSize().width;int height = this.getSize().height;Point x = new Point2D.Double(width/3,height/3);Point y = new

Point2D.Double(2*width/3,2*height/3);GradientPaint gp = newGradientPaint(x,y,Color.red,Color.green,cycle);g2d.setPaint(gp);// ...

}

Texture Painting The constructor for a TexturePaint object would

look as follows:public TexturePaint(BufferedImage txtbuffer,

Rectangle2D anchor); The BufferedImage object must be created from

an external source or by programmatically filled by using some sort of algorithm.

When the TexturePaint object is instantiated, an anchoring rectangle is specified in user space coordinates.

This acchoring rectangle (with its associated BufferedImage) is copied in both x and y directions infinitely across the shape to be rendered.

Managing Transparency a source over alpha composite object is created with an alpha

of .5 and added to the graphics context, causing subsequent shapes to

be rendered 50% transparent.

public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; // …// … // Create a new alpha composite

AlphaComposite ac =AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.5f); g2.setComposite(ac); // …// …}}