java2d and svg

60
Java 2D and SVG Rachel Struthers

Upload: josephchuahl

Post on 19-Nov-2014

152 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Java2d and SVG

Java 2D and SVG

Rachel Struthers

Page 2: Java2d and SVG

Topics Covered

Java 2D Rendering Basic Shapes Transformations

SVG(Scalable Vector Graphics) Basic drawing commands Some examples Batik Java library

Page 3: Java2d 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

Page 4: Java2d and SVG

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)

Page 5: Java2d and SVG

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)

Page 6: Java2d and SVG

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.

Page 7: Java2d and SVG

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

Page 8: Java2d and SVG

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!

Page 9: Java2d and SVG

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

Page 10: Java2d and SVG

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

Page 11: Java2d and SVG

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

Page 12: Java2d and SVG

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

Page 13: Java2d and SVG

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

Page 14: Java2d and SVG

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); }}

Page 15: Java2d and SVG

Not restricted to JPanel!

Can also use in JButton, JLabel Custom renderers for

JTable JComboBox Etc.

Page 16: Java2d and SVG

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

Page 17: Java2d and SVG

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

Page 18: Java2d and SVG

Graphics2D – setting attributes setStroke setPaint setComposite setTransform setClip setFont setRenderingHints

Page 19: Java2d and SVG

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

Page 20: Java2d and SVG

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

Page 21: Java2d and SVG

Drawing Shapes

Old AWT way (can still use) drawXxxx fillXxxx

OR - Create a Shape object and the draw or fill

Page 22: Java2d and SVG

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); }

Page 23: Java2d and SVG

Graphics2D draw and fill

Arguments to the draw and fill must implement the Shape interface

Graphics built using objects rather than instructions

Page 24: Java2d and SVG

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

Page 25: Java2d and SVG

Arc2D – three different close types

Open Pie Chord

Page 26: Java2d and SVG

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

Page 27: Java2d and SVG

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!”); }}

Page 28: Java2d and SVG

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

Page 29: Java2d and SVG

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 PaintingAndStroking.java

Page 30: Java2d and SVG

Paint Classes Color

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

Page 31: Java2d and SVG

Compositing

Process of putting two pictures together

Every time object is drawn, source and destination combination process is performed

Usually use source over destination

Page 32: Java2d and SVG

Compositing Rules

Page 33: Java2d and SVG

Transparency

Assign transparency (alpha) values to drawing operations

Underlying graphics show through Call setComposite of Graphics2D

object AlphaComposite.getInstance TransparencyExample.java (run-

transparency)

Page 34: Java2d and SVG

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

Page 35: Java2d and SVG

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]);

Page 36: Java2d and SVG

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

Page 37: Java2d and SVG

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)

Page 38: Java2d and SVG

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

Page 39: Java2d and SVG

Other Capabilities of Java 2D High-quality printing Improved XOR mode Custom color mixing Fancy text operations Low-level image processing

See JavaWorld article: http://www.javaworld.com/javaworld/jw-09-1998/jw

-09-media.html (download\media\run.bat) Animation -see example programs:

TextBouncer Bouncer

Page 40: Java2d and SVG

For More Information

Sun's page: http://java.sun.com/products/java-med

ia/2D/ Many of the examples were from

this book: Java 2D Graphics by Jonathan

Knudsen

Page 41: Java2d and SVG

Examples From Java SDK

Look in: C:\j2sdk1.4.1_02\demo\jfc\Java2D Open Java2Demo.html Source is included

Page 42: Java2d and SVG

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

https://sourceforge.net/projects/jfreechart/

Page 43: Java2d and 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

Page 44: Java2d and SVG

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

Page 45: Java2d and SVG

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

Page 46: Java2d and SVG

How to View

Adobe plugin: http://www.adobe.com/svg

/viewer/install/ Small and powerful Many examles on their website

Page 47: Java2d and SVG

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

Page 48: Java2d and SVG

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>

Page 49: Java2d and SVG

Filter Effects

Page 50: Java2d and SVG

Line Drawing Example

Page 51: Java2d and SVG

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" />

Page 52: Java2d and SVG

Line Example

Page 53: Java2d and SVG

Fancy SVG Examples

From kevlindev.com: Kaleidoscope

carto.net Weather map Fireworks Animated bus track Canvas and Layers

Page 54: Java2d and SVG

Batik

Open source Java API from Apache: http://xml.apache.org/batik/index.html

Render SVG files in Java application Write Java 2D to SVG file

Page 55: Java2d and SVG

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

Page 56: Java2d and SVG

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

Page 57: Java2d and SVG

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)

Page 58: Java2d and SVG

JSVG Canvas

Use to display SVG in a Java program

JSVGCanvasExample.java

JSVGCanvas canvas = new JSVGCanvas(); canvas.setURI( new

File(fileName).toURL().toString() );

Page 59: Java2d and SVG

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

Page 60: Java2d and SVG

SVG – More Information http://www.kevlindev.com/

Tutorials Examples

Batik http://xml.apache.org/batik/index.html

Adobe SVG Zone http://www.adobe.com/svg/main.html Browser plugin Examples

SVG Specification http://www.w3.org/TR/SVG/