Download presentation
Presentation is loading. Please wait.
1
Java 2D and SVG Rachel Struthers
2
Topics Covered Java 2D SVG(Scalable Vector Graphics) Rendering
Basic Shapes Transformations SVG(Scalable Vector Graphics) Basic drawing commands Some examples Batik Java library
3
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
4
Vector Graphics vs. 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)
5
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: ShowOff.java (from Java 2D book)
6
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.
7
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
8
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!
9
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
10
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
11
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
12
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
13
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
14
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(Color.blue); g2d.fillRect(20, 20, 100, 80); }
15
Not restricted to JPanel!
Can also use in JButton, JLabel Custom renderers for JTable JComboBox Etc.
16
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
17
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
18
Graphics2D – setting attributes
setStroke setPaint setComposite setTransform setClip setFont setRenderingHints
19
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
20
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
21
Drawing Shapes Old AWT way (can still use)
drawXxxx fillXxxx OR - Create a Shape object and the draw or fill
22
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); }
23
Graphics2D draw and fill
Arguments to the draw and fill must implement the Shape interface Graphics built using objects rather than instructions
24
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 JavaApplet2D.java
25
Arc2D – three different close types
Open Pie Chord
26
Lines Create a line using Line2D classes inner class constructors
Line2D.Float(), etc. Line2D.Double(), etc. StringArt.java QuadCurve2D 2 end points and a control points CubicCurve2D 2 end points and 2 control points DragKing.java
27
Bounds/Hit Testing Shape has various contains() methods
Makes for easy user interaction Java2DApplet.java public void mouseClicked(MouseEvent e) { Point2D point = new Point2D.Double(e.getX(), e.getY()); if (shape.contains(point)) showMessage(“Hit me!”); }
28
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); CombiningShapes.java
29
Painting Paint attribute of Graphics2D PaintingAndStroking.java
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 PaintingAndStroking.java
30
Paint Classes Color GradientPaint TexturePaint Solid color
Same constants as in AWT: Color.red, Color.black, etc. Java2DApplet.java GradientPaint Gradient fill gradually combining two colors Can create your own RoundGradientPaint.java TexturePaint Tiled image TexturePaintFill.java
31
Compositing Process of putting two pictures together
Every time object is drawn, source and destination combination process is performed Usually use source over destination
32
Compositing Rules
33
Transparency Assign transparency (alpha) values to drawing operations
Underlying graphics show through Call setComposite of Graphics2D object AlphaComposite.getInstance TransparencyExample.java (run-transparency)
34
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
35
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]);
36
Drawing With Local Fonts - Example
Query the available fonts using getAvailableFontNames of GraphicsEnvironment Set the font in the Graphcis2D object Call g2d.drawString method ShowFonts.java
37
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) StrokePanel.java (Java2DApplet.java)
38
Coordinate Transformations
Java 2D allows you to easily Translate Rotate Scale Shear Use java.awt.geom.AffineTransform Example from Java 2D book: Transformers.java and other classes Creates a GeneralPath object Transform using the above operations
39
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
40
For More Information Sun's page:
Many of the examples were from this book: Java 2D Graphics by Jonathan Knudsen
41
Examples From Java SDK Look in: C:\j2sdk1.4.1_02\demo\jfc\Java2D
Open Java2Demo.html Source is included
42
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 demo.jar
43
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
44
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
45
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
46
How to View Adobe plugin: http://www.adobe.com/svg/viewer/install/
Small and powerful Many examles on their website
47
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
48
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>
49
Filter Effects
50
Line Drawing Example
51
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" />
52
Line Example
53
Fancy SVG Examples From kevlindev.com: carto.net Kaleidoscope
Weather map Fireworks Animated bus track Canvas and Layers
54
Batik Open source Java API from Apache:
Render SVG files in Java application Write Java 2D to SVG file
55
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
56
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
57
Batik Core Modules SVG Generator SVG DOM JSVGCanvas Transcoder
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)
58
JSVG Canvas Use to display SVG in a Java program
JSVGCanvasExample.java JSVGCanvas canvas = new JSVGCanvas(); canvas.setURI( new File(fileName).toURL().toString() );
59
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
60
SVG – More Information http://www.kevlindev.com/ Batik Adobe SVG Zone
Tutorials Examples Batik Adobe SVG Zone Browser plugin SVG Specification
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.