1 / 25

Lecture07

Lecture07. Graphics Programming in Java. Introduction. Most of the graphics programming of java is done with: Java AWT - The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. This is the very first GUI support Java had.

Download Presentation

Lecture07

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture07 Graphics Programming in Java

  2. Introduction • Most of the graphics programming of java is done with: • Java AWT - The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. This is the very first GUI support Java had. • Swing – An advanced GUI library designed to overcome limitations of AWT. • Java2D - The Java 2DTM API is a set of classes for advanced 2D graphics and imaging. It encompasses line art, text, and images in a single comprehensive model. These classes are provided as additions to the java.awt and java.awt.image packages.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. Example – 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 gc for (int i=0; i < gc.length; i++) { Rectangle virtualBounds = new Rectangle(); virtualBounds = gc[i].getBounds(); // Display details of virtualBounds } }

  8. Rendering with Graphics and Graphics2D • There is a three-step recipe for writing a graphics program in Java. • Get a graphics context. • Set or Modify the context. • Render something.

  9. 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.

  10. Example public void paint(Graphics g) { // Cast the Graphics object to access the increased // functionality of Java2D Graphics2D g2d = (Graphics2D) g; // Set or Modify the graphics context g2d.setColor(Color.red); // Render something g2d.fill(new Rectangle2D.Float(200.0f,200.0f,75.0f,75.0f)); }

  11. 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.

  12. 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.

  13. 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.

  14. An example rendering on a JButton: class myCustomButton extends JButton { public void paint(Graphics g) { // Step one: Cast the Graphics object as Graphics2D Graphics2D g2d = (Graphics2D) g; // make the GradientPaint object going from blue to green // across from top left to bottom right GradientPaint gp = new GradientPaint(0,0,Color.blue, this.getSize().width/20, this.getSize().height/20, Color.green, true); // Step two: set the graphics context g2d.setPaint(gp); // Render something g2d.fill(new Rectangle2D.Float(0.0f,0.0f,75.0f,75.0f)); } }

  15. 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.

  16. Example public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; // cast the graphics object g2d.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 point gp.append(new Rectangle2D.Float((float)cwidth/2, (float)cheight/2,20.0f,45.0f),true); // append a rectangle gp.lineTo((int)cwidth/4, (int)cheight/4); // line segment gp.append(new Ellipse2D.Float((float)0.9*cwidth, (float)0.25*cheight,20.0f,45.0f),true); // append a ellipse gp.closePath(); g2d.draw(gp); // Render the graphics reportGP(gp); }

  17. Example // Report about each segment as we go along the general path public 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(); } }

  18. 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.

  19. Example code segment public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; // Create some graphics GeneralPath gp = new GeneralPath(); // build gp BasicStroke stroke = new BasicStroke(10); // set line thickness to 10 // modify graphics context - change the stroke g2d.setStroke(stroke); g2d.draw(gp); // render graphics }

  20. 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.

  21. Solid Color Painting • To user-define predefined color objects Color 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);

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

  23. An Example: Gradient Painting public 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 = new GradientPaint(x,y,Color.red,Color.green,cycle); g2d.setPaint(gp); // ... }

  24. 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.

  25. 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); // … }

More Related