Java 2D and SVG

67 %
33 %
Information about Java 2D and SVG

Published on May 12, 2007

Author: TSBaG


Java 2D and SVG:  Java 2D and SVG Rachel Struthers Topics Covered:  Topics Covered Java 2D Rendering Basic Shapes Transformations SVG(Scalable Vector Graphics) Basic drawing commands Some examples Batik Java library Java 2D and SVG:  Java 2D and SVG Vector based rather than pixel based Both can be used on the web to show high-quality interactive graphcis Java 2D – produce vector graphics using code API in Java 1.2 and above SVG – produce vector graphics using XML Vector Graphics vs. Raster Graphics:  Vector Graphics vs. Raster Graphics Raster Graphics Pixel based – high bandwidth Resolution dependent, picture from workstation might not work on PDA Examples: GIF, JPEG, BMP Vector Graphics Command based – low bandwidth Resolution independent = scalable, zoomable without loss of quality Examples: SVG, SWF (Flash), EPS (Encapsulated Postscript) What is Java 2D?:  What is Java 2D? API included with JDK Line art Text Imaging Allows you to easily Draw lines of any thickness Fill shapes with gradients and textures Move, rotate, scale, and shear text and graphics Composite overlapping text and graphics Example: (from Java 2D book) Where Can I Use Java 2D?:  Where Can I Use Java 2D? Any Java 2 type application Included in Java 1.2 or above Stand-alone rich-client applications Web applications (applets) Servers side generation of dynamic images suchs as maps, charts, etc. What Are Prerequisites for Using?:  What Are Prerequisites for Using? Basic Java programming Some OO knowledge Need to have basic grasp of interfaces for: Shape Paint Some exposure to graphics or user interface programing helpful AWT or Swing Graphics in other languages Think Paint!:  Think Paint! When using Java 2D, keep in mind the rendering pipeline Nothing is shown until paint is called Must extend an object that is of the Component family Override paint() method No painting – no picture! When is paint() called for a component?:  When is paint() called for a component? System triggered: When the component is first shown When it is “damaged” (covered by a window and then uncovered, for example) Component resized App triggered: When a program calls repaint State of button has changed Date (model) has changed Paint in Swing or AWT Components:  Paint in Swing or AWT Components For AWT, can override Canvas, Panel paint methods Other things that inherit from Component For Swing Extend JPanel, JButton, etc Other things that inherit from JComponent How to use in AWT:  How to use in AWT Extend a component such as Canvas or Panel Override public void paint(Graphics g) If extending a container call super.paint(g) so that children are painted Rest of the discussion uses Swing components How to use in Swing Components:  How to use in Swing Components Extend a Swing component such as JPanel Override paintComponent Cast Graphics to Graphics2D so you can use advanced features Make sure you call super.paintComponent(g) as first call! Or funny things happen Ghosts, background wrong Methods Called for Swing Refresh:  Methods Called for Swing Refresh In Swing paint() still gets called when it's time to render Work of paint is divided into three methods protected void paintComponent(Graphics g) protected void paintBorder(Graphics g) protected void paintChildren(Graphics g) Generally you only override paintComponent Basic Java 2D:  Basic Java 2D public MyBasicDrawPanel extends JPanel { protected void paintComponent(Graphics g) { // Call super.paintComponent! super.paintComponent(g); // Cast Graphics to Graphics2D Graphics2D g2d = (Graphics2D)g; // Draw g2d.setColor(; g2d.fillRect(20, 20, 100, 80); } } Not restricted to JPanel! :  Not restricted to JPanel! Can also use in JButton, JLabel Custom renderers for JTable JComboBox Etc. Painting Tips :  Painting Tips Be polite: trigger a repaint (as when data model changes) by calling repaint not paint Puts a request in the event queue If drawing is complex, try to repaint only the area that needs updating Use void repaint(Rectangle r) not void repaint() (paints the whole thing) For paintComponent method, always call super.paintComponent first! Make use of clipping to enhance performance Graphics2D object:  Graphics2D object Java 2D's extension of Graphics object Used to draw Shape objects Has rendering attributes: Pen Style (solid, dotted, dashed) Fill Compositing (used when objects overlap) Transform (scale, rotate, translate, shear) Clip area Font Rendering hints Graphics2D – setting attributes:  Graphics2D – setting attributes setStroke setPaint setComposite setTransform setClip setFont setRenderingHints Graphics2D Rendering Methods:  Graphics2D Rendering Methods draw renders outline of graphics primitive using stroke and paint attributes fill fills shape with given paint attribute (color or pattern) drawString draw string with given font and paint attribute drawImage draw an image Shape Interface:  Shape Interface To draw, use things that implement Shape such as: Area CubicCurve2D GeneralPath Line2D Polygon QuadCurve2D Rectangle RectangularShape These use double's or float's for parameters Drawing Shapes:  Drawing Shapes Old AWT way (can still use) drawXxxx fillXxxx OR - Create a Shape object and the draw or fill Creating Shapes:  Creating Shapes public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; // Assume x, y, and diameter are instance variables Ellipse2D.Double circle = new Ellipse2D.double(x, y, diameter, diameter); g2d.fill(circle); } Graphics2D draw and fill:  Graphics2D draw and fill Arguments to the draw and fill must implement the Shape interface Graphics built using objects rather than instructions Rectangles, Ellipses and ARcs:  Rectangles, Ellipses and ARcs Note that many Shape classes have inner constructors Use Rectangle2D inner classes to create: Rectangle2D.Double Retangle2D.Float Ellipse2D: Ellipse2D.Double Ellipse2D.Float Arc2D Arc2D.Double Arc2D.Float See Arc2D – three different close types:  Arc2D – three different close types Open Pie Chord Lines:  Lines Create a line using Line2D classes inner class constructors Line2D.Float(), etc. Line2D.Double(), etc. QuadCurve2D 2 end points and a control points CubicCurve2D 2 end points and 2 control points Bounds/Hit Testing:  Bounds/Hit Testing Shape has various contains() methods Makes for easy user interaction public void mouseClicked(MouseEvent e) { Point2D point = new Point2D.Double(e.getX(), e.getY()); if (shape.contains(point)) { showMessage(“Hit me!”); } } Combining Shapes:  Combining Shapes Combine Shape objects using the Area class Area implements Shape – can draw using Graphics2D Create: new Area() or new Area(Shape s) Combine: public void add(Area a) public void intersect(Area a); public void subtract(Area a); public void exclusiveOr(Area a); Painting:  Painting Paint attribute of Graphics2D Goes way beyond the old color attribute (still useable) getPaint, setPaint Used when fill method is called on a shape Arguments to setPaint must implement the Paint interface Paint Classes:  Paint Classes Color Solid color Same constants as in AWT:,, etc. GradientPaint Gradient fill gradually combining two colors Can create your own TexturePaint Tiled image Compositing:  Compositing Process of putting two pictures together Every time object is drawn, source and destination combination process is performed Usually use source over destination Compositing Rules:  Compositing Rules Transparency:  Transparency Assign transparency (alpha) values to drawing operations Underlying graphics show through Call setComposite of Graphics2D object AlphaComposite.getInstance (run-transparency) Using Local Fonts:  Using Local Fonts Same logical fonts as in Java 1.1 Serif, SansSerif, Monospaced, Dialog, DialogInput Also, arbitrary local fonts Must lookup entire list May take awhile Use GraphicsEnvironment methods getAvailableFontFamilyNames getAllFonts Printing All Font Names:  Printing All Font Names GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] fontNames = env.getAvailableFontFamilyName(); System.out.println("Available Fonts:"); for(int i=0; i<fontNames.length; i++) System.out.println(" " + fontNames[i]); Drawing With Local Fonts - Example:  Drawing With Local Fonts - Example Query the available fonts using getAvailableFontNames of GraphicsEnvironment Set the font in the Graphcis2D object Call g2d.drawString method Stroke Styles in Java 2D:  Stroke Styles in Java 2D In AWT, could only do 1-pixel wide lines, no control over how lines are joined Much more flexibility in Java2D – can specify: Pen thickness Dashing pattern The way line segments are joined together Create a BasicStroke object (several contructors) ( Coordinate Transformations:  Coordinate Transformations Java 2D allows you to easily Translate Rotate Scale Shear Use java.awt.geom.AffineTransform Example from Java 2D book: and other classes Creates a GeneralPath object Transform using the above operations Other Capabilities of Java 2D:  Other Capabilities of Java 2D High-quality printing Improved XOR mode Custom color mixing Fancy text operations Low-level image processing See JavaWorld article: (download\media\run.bat) Animation -see example programs: TextBouncer Bouncer For More Information:  For More Information Sun's page: Many of the examples were from this book: Java 2D Graphics by Jonathan Knudsen Examples From Java SDK:  Examples From Java SDK Look in: C:\j2sdk1.4.1_02\demo\jfc\Java2D Open Java2Demo.html Source is included JFreeChart :  JFreeChart Example of someone using Java2D API Open source Java API For creating charts and graphs Has example of generating chart in servlet Also has demo that shows several different kinds of charts jfreechart-0.9.14-demo.jar What is SVG?:  What is SVG? Scalable Vector Graphics Language for describing two-dimensioal graphics and graphical applications in XML Created by the World Wide Web Consortium (W3C) Over 20 organizations including Sun Microsystems, Adobe, Apple and IBM involved Sun active from the start SVG Features:  SVG Features Plain text format (not some complicated binary form) Low band-width Scalable – unlike GIF and JPEG Zoomable – picture just as clear Searchable and selectable text (unlike bitmaps) Scripting and animation Works with Java! Open Standard True XML SVG on the Web:  SVG on the Web Can easily be generated on web servers “on the fly” Example: create a high quality, low bandwith stock quote graph SVG can be created: Through a drawing package Or by writing code Or Notepad How to View:  How to View Adobe plugin: Small and powerful Many examles on their website SVG Tag Sampling:  SVG Tag Sampling Shape Tags: <line>, <rect>, <circle>, <ellipse>, <polyline>, <polygon>, <path> Paint Tags: <linearGradient>, <radialGradient>, <pattern>, <mask> Text Tags: <text>, <tspan>, <textPath>, <font>, <font-face>, <glyph> Filter Tags: <filter>, <feBlend>, <feFlood>, <feColorMatrix>, <feGaussianBlur> <feMorphology> <feSpotLight> Animation Tags: <animate>, <animateMotion>, <animateTransform>, <animateColor>, <set> Misc Tags: <image>, <symbol>, <g>, <defs>, <use> And Much More SVG in Action:  SVG in Action <svg> <g style="fill-opacity:0.7; stroke:black; stroke-width:0.1cm;"> <circle cx="6cm" cy="2cm" r="100" style="fill:red;" transform="translate(0,50)" /> <circle cx="6cm" cy="2cm" r="100" style="fill:blue;" transform="translate(70,150)" /> <circle cx="6cm" cy="2cm" r="100" style="fill:green;" transform="translate(-70,150)"/> </g> </svg> Filter Effects:  Filter Effects Line Drawing Example:  Line Drawing Example Basic SVG Shapes:  Basic SVG Shapes <line x1="start-x" y1="start-y" x2="end-x" y2="end-y" /> <rect x="left-x" y="top-y" width="width" height="height" /> <circle cx="center-x" cy="center-y" r="radius" /> <ellipse cx="center-x" cy="center-y" rx="x-radius" ry="y-radius" /> <polygon points="points" /> <polyline points="points" /> Line Example:  Line Example Fancy SVG Examples:  Fancy SVG Examples From Kaleidoscope Weather map Fireworks Animated bus track Canvas and Layers Batik:  Batik Open source Java API from Apache: Render SVG files in Java application Write Java 2D to SVG file Batik Application Modules:  Batik Application Modules SVG Browser View, zoom, pan an rotate SVG documents SVG Pretty Printer Tidy up messay SVG SVG Font Converter Convert from True Type to SVG font format SVG Rasterizer Convert to and from SVG content SVG Browser - Squiggle:  SVG Browser - Squiggle Java program included in Batik release batik-squiggle.jar If Java installed – simple double-click to run Allows you to view SVG files – zoom, search text View many sample SVG files that come with Batik sizeofsun – search for Pluto Batik Core Modules:  Batik Core Modules SVG Generator SVGCanvas2D Java 2D “draws” to an SVG file SVG DOM Manipulate SVG documents in a Java program JSVGCanvas Display SVG content in a Java panel Transcoder Save SVG in another format (such as JPEG) JSVG Canvas:  JSVG Canvas Use to display SVG in a Java program JSVGCanvas canvas = new JSVGCanvas(); canvas.setURI( new File(fileName).toURL().toString() ); SVG Generator:  SVG Generator Write any arbitray Java 2D graphics to SVG Can then view in browser with SVG plugin Uses SVGGraphics2D Similar to Grahpics2D in Java 2D Write to an XML file instead of printer or screen SVG – More Information:  SVG – More Information Tutorials Examples Batik Adobe SVG Zone Browser plugin Examples SVG Specification

Add a comment

Related presentations

Related pages

Bringing SVG Power to Java Applications - Oracle

Learn how to build SVG libraries and applications on top of the Java platform. The article takes you step-by-step through an example that uses ...
Read more

SVG and the Java 2D API -

In this article, the author of the Graphics 2D SVG Generator explains how it takes advantage of the Java 2D API's extensible architecture, and how any Java ...
Read more

Trail: 2D Graphics (The Java™ Tutorials) - Oracle

This 2d Java tutorial describes 2d graphics, geometry, text APIs, images, printing, advanced 2d topics
Read more

SVG Generator: SVGGraphics2D

If you integrate the Batik SVG generator in your own Java application, ... The SVGGraphics2D is able to generate SVG elements for generic Java 2D objects, ...
Read more

Scalable 2D Vector Graphics API | SAMSUNG Developers

Introduction. This Article introduces the Scalable 2D Vector Graphics API, an optional package you can use with Java 2 Platform, Micro Edition (J2ME) profiles.
Read more

Java 2D - Oracle

The Java 2D API is a set of classes for advanced 2D graphics and imaging, encompassing line art, text, and images in a single comprehensive model.
Read more

Grafikausgabe mit Java (AWT, Java 2D ... -

Das Java 2D API beinhaltet in einem einheitlichen umfassenden Modell Klassen für ... Falls von Ihrer SVG-Grafik nur ein Ausschnitt ...
Read more Java + Sie

Erhalten Sie die aktuellste Java-Software und entdecken Sie das verbesserte digitale Erlebnis der Java-Technologie.
Read more

SVG For Teaching 2D Graphics Standards -

SVG For Teaching 2D Graphics Standards. Keywords: computer graphics curriculum, SVG, graphical modelling, case studies, visualization, image processing, ...
Read more

Java2d and SVG -

Java2d and SVG - Download as Powerpoint Presentation (.ppt), PDF File (.pdf), Text File (.txt) or view presentation slides online.
Read more