- java.lang.Object
-
- processing.core.PShape
-
- processing.core.PShapeSVG
-
- All Implemented Interfaces:
PConstants
- Direct Known Subclasses:
PShapeSVG.Font,PShapeSVG.FontGlyph,PShapeSVG.Gradient,PShapeSVG.LineOfText,PShapeSVG.Text
public class PShapeSVG extends PShape
This class is not part of the Processing API and should not be used directly. Instead, use loadShape() and methods like it, which will make use of this class. Using this class directly will cause your code to break when combined with future versions of Processing.SVG stands for Scalable Vector Graphics, a portable graphics format. It is a vector format so it allows for "infinite" resolution and relatively small file sizes. Most modern media software can view SVG files, including Adobe products, Firefox, etc. Illustrator and Inkscape can edit SVG files. View the SVG specification here.
We have no intention of turning this into a full-featured SVG library. The goal of this project is a basic shape importer that originally was small enough to be included with applets, meaning that its download size should be in the neighborhood of 25-30 Kb. Though we're far less limited nowadays on size constraints, we remain extremely limited in terms of time, and do not have volunteers who are available to maintain a larger SVG library.
For more sophisticated import/export, consider the Batik library from the Apache Software Foundation.
Batik is used in the SVG Export library in Processing 3, however using it for full SVG import is still a considerable amount of work. Wiring it to Java2D wouldn't be too bad, but using it with OpenGL, JavaFX, and features like begin/endRecord() and begin/endRaw() would be considerable effort.
Future improvements to this library may focus on this properly supporting a specific subset of SVG, for instance the simpler SVG profiles known as SVG Tiny or Basic, although we still would not support the interactivity options.
A minimal example program using SVG: (assuming a working moo.svg is in your data folder)
PShape moo; void setup() { size(400, 400); moo = loadShape("moo.svg"); } void draw() { background(255); shape(moo, mouseX, mouseY); }
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classPShapeSVG.Fontstatic classPShapeSVG.FontGlyphstatic classPShapeSVG.Gradientstatic classPShapeSVG.LinearGradientstatic classPShapeSVG.LineOfTextstatic classPShapeSVG.RadialGradientstatic classPShapeSVG.Text
-
Field Summary
Fields Modifier and Type Field Description protected static IntDictcolorNamesDeliberately conforms to the HTML 4.01 color spec + en-gb grey, rather than the (unlikely to be useful) entire 147-color system used in SVG.protected PShapeSVG.GradientfillGradientprotected floatopacityprotected PShapeSVG.GradientstrokeGradientprotected floatsvgHeightHeight of containing SVG (used for percentages).protected floatsvgSizeXY√((w² + h²)/2) of containing SVG (used for percentages).protected floatsvgWidthWidth of containing SVG (used for percentages).-
Fields inherited from class processing.core.PShape
ambientColor, calcA, calcAi, calcAlpha, calcB, calcBi, calcColor, calcG, calcGi, calcR, calcRi, childCount, children, close, colorMode, colorModeA, colorModeX, colorModeY, colorModeZ, depth, ellipseMode, emissiveColor, family, fill, fillColor, GEOMETRY, height, image, imagePath, INSIDE_BEGIN_END_ERROR, is3D, kind, matrix, name, nameTable, NO_SUCH_VERTEX_ERROR, NO_VERTICES_ERROR, NOT_A_SIMPLE_VERTEX, openContour, openShape, OUTSIDE_BEGIN_END_ERROR, params, parent, PATH, PER_VERTEX_UNSUPPORTED, perVertexStyles, PRIMITIVE, rectMode, setAmbient, shininess, specularColor, sphereDetailU, sphereDetailV, stroke, strokeCap, strokeColor, strokeJoin, strokeWeight, style, textureMode, tint, tintColor, vertexCodeCount, vertexCodes, vertexCount, vertices, visible, width
-
Fields inherited from interface processing.core.PConstants
ADD, ALPHA, ALT, AMBIENT, ARC, ARGB, ARROW, BACKSPACE, BASELINE, BEVEL, BEZIER_VERTEX, BLEND, BLUR, BOTTOM, BOX, BREAK, BURN, CENTER, CHATTER, CHORD, CLAMP, CLOSE, CODED, COMPLAINT, CONTROL, CORNER, CORNERS, CROSS, CURVE_VERTEX, CUSTOM, DARKEST, DEG_TO_RAD, DELETE, DIAMETER, DIFFERENCE, DILATE, DIRECTIONAL, DISABLE_ASYNC_SAVEFRAME, DISABLE_BUFFER_READING, DISABLE_DEPTH_MASK, DISABLE_DEPTH_SORT, DISABLE_DEPTH_TEST, DISABLE_KEY_REPEAT, DISABLE_NATIVE_FONTS, DISABLE_OPENGL_ERRORS, DISABLE_OPTIMIZED_STROKE, DISABLE_STROKE_PERSPECTIVE, DISABLE_STROKE_PURE, DISABLE_TEXTURE_MIPMAPS, DODGE, DOWN, DXF, ELLIPSE, ENABLE_ASYNC_SAVEFRAME, ENABLE_BUFFER_READING, ENABLE_DEPTH_MASK, ENABLE_DEPTH_SORT, ENABLE_DEPTH_TEST, ENABLE_KEY_REPEAT, ENABLE_NATIVE_FONTS, ENABLE_OPENGL_ERRORS, ENABLE_OPTIMIZED_STROKE, ENABLE_STROKE_PERSPECTIVE, ENABLE_STROKE_PURE, ENABLE_TEXTURE_MIPMAPS, ENTER, EPSILON, ERODE, ESC, EXCLUSION, FX2D, GIF, GRAY, GROUP, HALF_PI, HAND, HARD_LIGHT, HINT_COUNT, HSB, IMAGE, INVERT, JAVA2D, JPEG, LANDSCAPE, LEFT, LIGHTEST, LINE, LINE_LOOP, LINE_STRIP, LINES, LINUX, MACOSX, MAX_FLOAT, MAX_INT, MIN_FLOAT, MIN_INT, MITER, MODEL, MODELVIEW, MOVE, MULTIPLY, NORMAL, OPAQUE, OPEN, OPENGL, ORTHOGRAPHIC, OTHER, OVERLAY, P2D, P3D, PDF, PERSPECTIVE, PI, PIE, platformNames, POINT, POINTS, POLYGON, PORTRAIT, POSTERIZE, PROBLEM, PROJECT, PROJECTION, QUAD, QUAD_BEZIER_VERTEX, QUAD_STRIP, QUADRATIC_VERTEX, QUADS, QUARTER_PI, RAD_TO_DEG, RADIUS, RECT, REPEAT, REPLACE, RETURN, RGB, RIGHT, ROUND, SCREEN, SHAPE, SHIFT, SOFT_LIGHT, SPAN, SPHERE, SPOT, SQUARE, SUBTRACT, SVG, TAB, TARGA, TAU, TEXT, THIRD_PI, THRESHOLD, TIFF, TOP, TRIANGLE, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP, VERTEX, WAIT, WHITESPACE, WINDOWS, X, Y, Z
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description protected static PFontcreateFont(String name, int weight, float size, boolean smooth)protected PShapeSVGcreateShape(PShapeSVG parent, XML properties, boolean parseKids)Factory method for subclasses.PShapegetChild(String name)Get a particular element based on its SVG ID.protected static floatgetFloatWithUnit(XML element, String attribute, float relativeTo)Used in place of element.getFloatAttribute(a) because we can have a unit suffix (length or coordinate).protected PShapeparseChild(XML elem)Parse a child XML element.protected voidparseChildren(XML graphics)protected voidparseColors(XML properties)protected voidparseEllipse(boolean circle)Handles parsing ellipse and circle tags.protected static floatparseFloatOrPercent(String text)protected voidparseImage()protected voidparseLine()protected voidparsePath()protected voidparsePoly(boolean close)Parse a polyline or polygon from an SVG file.protected voidparseRect()protected static intparseRGB(String what)protected static intparseSimpleColor(String colorText)Parses the "color" datatype only, and prints an error if it is not of this form.protected static PMatrix2DparseSingleTransform(String matrixStr)protected static StringDictparseStyleAttributes(String style)protected static PMatrix2DparseTransform(String matrixStr)Parse the specified SVG matrix into a PMatrix2D.protected static floatparseUnitSize(String text, float relativeTo)Parse a size that may have a suffix for its units.voidprint()Prints out the SVG document.protected voidsetParent(PShapeSVG parent)-
Methods inherited from class processing.core.PShape
addChild, addChild, addName, ambient, ambient, ambient, applyMatrix, applyMatrix, applyMatrix, applyMatrix, applyMatrix, attrib, attrib, attrib, attribColor, attribNormal, attribPosition, beginContour, beginContourImpl, beginShape, beginShape, bezierDetail, bezierVertex, bezierVertex, checkMatrix, colorCalc, colorCalc, colorCalc, colorCalc, colorCalc, colorCalc, colorCalcARGB, colorMode, colorMode, colorMode, colorMode, contains, copyGeometry, copyGroup, copyImage, copyMatrix, copyPath, copyPrimitive, copyStyles, createShape, crop, curveDetail, curveTightness, curveVertex, curveVertex, disableStyle, draw, drawGeometry, drawGroup, drawImpl, drawPath, drawPrimitive, emissive, emissive, emissive, enableStyle, endContour, endContourImpl, endShape, endShape, fill, fill, fill, fill, fill, fill, findChild, getAmbient, getChild, getChildCount, getChildIndex, getChildren, getDepth, getEmissive, getFamily, getFill, getHeight, getKind, getName, getNormal, getNormal, getNormalX, getNormalY, getNormalZ, getParam, getParams, getParams, getParent, getShininess, getSpecular, getStroke, getStrokeWeight, getTessellation, getTextureU, getTextureV, getTint, getVertex, getVertex, getVertexCode, getVertexCodeCount, getVertexCodes, getVertexCount, getVertexX, getVertexY, getVertexZ, getWidth, is2D, is3D, isClosed, isVisible, noFill, normal, noStroke, noTexture, noTint, post, pre, quadraticVertex, quadraticVertex, removeChild, resetMatrix, rotate, rotate, rotateX, rotateY, rotateZ, scale, scale, scale, set3D, setAmbient, setAmbient, setAttrib, setAttrib, setAttrib, setEmissive, setEmissive, setFamily, setFill, setFill, setFill, setKind, setName, setNormal, setParams, setPath, setPath, setShininess, setShininess, setSpecular, setSpecular, setStroke, setStroke, setStroke, setStrokeCap, setStrokeJoin, setStrokeWeight, setStrokeWeight, setTexture, setTextureMode, setTextureUV, setTint, setTint, setTint, setVertex, setVertex, setVertex, setVisible, shininess, solid, specular, specular, specular, stroke, stroke, stroke, stroke, stroke, stroke, strokeCap, strokeJoin, strokeWeight, styles, texture, textureMode, tint, tint, tint, tint, tint, tint, translate, translate, vertex, vertex, vertex, vertex
-
-
-
-
Field Detail
-
opacity
protected float opacity
-
svgWidth
protected float svgWidth
Width of containing SVG (used for percentages).
-
svgHeight
protected float svgHeight
Height of containing SVG (used for percentages).
-
svgSizeXY
protected float svgSizeXY
√((w² + h²)/2) of containing SVG (used for percentages).
-
strokeGradient
protected PShapeSVG.Gradient strokeGradient
-
fillGradient
protected PShapeSVG.Gradient fillGradient
-
colorNames
protected static IntDict colorNames
Deliberately conforms to the HTML 4.01 color spec + en-gb grey, rather than the (unlikely to be useful) entire 147-color system used in SVG.
-
-
Method Detail
-
setParent
protected void setParent(PShapeSVG parent)
-
createShape
protected PShapeSVG createShape(PShapeSVG parent, XML properties, boolean parseKids)
Factory method for subclasses.
-
parseChildren
protected void parseChildren(XML graphics)
-
parseChild
protected PShape parseChild(XML elem)
Parse a child XML element. Override this method to add parsing for more SVG elements.
-
parseLine
protected void parseLine()
-
parseEllipse
protected void parseEllipse(boolean circle)
Handles parsing ellipse and circle tags.- Parameters:
circle- true if this is a circle and not an ellipse
-
parseRect
protected void parseRect()
-
parseImage
protected void parseImage()
-
parsePoly
protected void parsePoly(boolean close)
Parse a polyline or polygon from an SVG file. Syntax defined at http://www.w3.org/TR/SVG/shapes.html#PointsBNF- Parameters:
close- true if shape is closed (polygon), false if not (polyline)
-
parsePath
protected void parsePath()
-
parseTransform
protected static PMatrix2D parseTransform(String matrixStr)
Parse the specified SVG matrix into a PMatrix2D. Note that PMatrix2D is rotated relative to the SVG definition, so parameters are rearranged here. More about the transformation matrices in this section of the SVG documentation.- Parameters:
matrixStr- text of the matrix param.- Returns:
- a good old-fashioned PMatrix2D
-
parseColors
protected void parseColors(XML properties)
-
parseSimpleColor
protected static int parseSimpleColor(String colorText)
Parses the "color" datatype only, and prints an error if it is not of this form. http://www.w3.org/TR/SVG/types.html#DataTypeColor- Returns:
- 0xRRGGBB (no alpha). Zero on error.
-
parseRGB
protected static int parseRGB(String what)
-
parseStyleAttributes
protected static StringDict parseStyleAttributes(String style)
-
getFloatWithUnit
protected static float getFloatWithUnit(XML element, String attribute, float relativeTo)
Used in place of element.getFloatAttribute(a) because we can have a unit suffix (length or coordinate).- Parameters:
element- what to parseattribute- name of the attribute to getrelativeTo- (float) Used for %. When relative to viewbox, should be svgWidth for horizontal dimentions, svgHeight for vertical, and svgXYSize for anything else.- Returns:
- unit-parsed version of the data
-
parseUnitSize
protected static float parseUnitSize(String text, float relativeTo)
Parse a size that may have a suffix for its units. This assumes 90dpi, which implies, as given in the units spec:- "1pt" equals "1.25px" (and therefore 1.25 user units)
- "1pc" equals "15px" (and therefore 15 user units)
- "1mm" would be "3.543307px" (3.543307 user units)
- "1cm" equals "35.43307px" (and therefore 35.43307 user units)
- "1in" equals "90px" (and therefore 90 user units)
- Parameters:
relativeTo- (float) Used for %. When relative to viewbox, should be svgWidth for horizontal dimentions, svgHeight for vertical, and svgXYSize for anything else.
-
parseFloatOrPercent
protected static float parseFloatOrPercent(String text)
-
getChild
public PShape getChild(String name)
Get a particular element based on its SVG ID. When editing SVG by hand, this is the id="" tag on any SVG element. When editing from Illustrator, these IDs can be edited by expanding the layers palette. The names used in the layers palette, both for the layers or the shapes and groups beneath them can be used here.// This code grabs "Layer 3" and the shapes beneath it. PShape layer3 = svg.getChild("Layer 3");
-
print
public void print()
Prints out the SVG document. Useful for parsing.
-
-