Class Svg
- All Implemented Interfaces:
Paintable, SymbolicPaintable, Proxy
A paintable implementation that renders SVG, with animations.
GtkSvg objects are created by parsing a subset of SVG,
including SVG animations.
GtkSvg fills or strokes paths with symbolic or fixed colors.
It can have multiple states, and paths can be included in a subset
of the states. States can have animations, and the transition
between different states can also be animated.
To show a static SVG image, it is enough to load the the SVG and use it like any other paintable.
To play an SVG animation, use setFrameClock(FrameClock)
to connect the paintable to a frame clock, and call
play() after loading the SVG. The animation can
be paused using pause().
To set the current state, use setState(int).
Error handling
Loading an SVG into GtkSvg will always produce a (possibly empty)
paintable. GTK will drop things that it can't handle and try to make
sense of the rest.
To track errors during parsing or rendering, connect to the
Gtk.Svg::error signal.
For parsing errors in the GTK_SVG_ERROR domain, the functions
SvgError.getStart(GError), SvgError.getEnd(GError),
SvgError.getElement(GError) and SvgError.getAttribute(GError)
can be used to obtain information about where the error occurred.
The supported subset of SVG
The paintable supports much of SVG 2, with some exceptions.
Among the graphical elements, <textPath> and <foreignObject>
are not supported.
Among the structural elements, <a> and <view> are not supported.
In the <filter> element, the following primitives are not
supported: feConvolveMatrix, feDiffuseLighting,
feMorphology, feSpecularLighting and feTurbulence.
Support for the mask attribute is limited to just a url
referring to the <mask> element by ID.
In animation elements, the parsing of begin and end attributes
is limited, and the min and max attributes are not supported.
Lastly, there is only minimal CSS support (the style attribute,
but not <style>), and no interactivity.
SVG Extensions
The paintable supports a number of custom attributes that offer a convenient way to define states, transitions and animations. For example,
<circle cx='5' cy='5' r='5'
gpa:states='0 1'
gpa:animation-type='automatic'
gpa:animation-direction='segment'
gpa:animation-duration='600ms'/>
defines the circle to be shown in states 0 and 1, and animates a segment of the circle.
Note that the generated animations are implemented using standard
SVG attributes (visibility, stroke-dasharray, stroke-dashoffset, pathLengthandfilter`). Setting these attributes in your SVG
is therefore going to interfere with generated animations.
To connect general SVG animations to the states of the paintable,
use the custom gpa:states(...) condition in the begin and end
attributes of SVG animation elements. For example,
<animate href='path1'
attributeName='fill'
begin='gpa:states(0).begin'
dur='300ms'
fill='freeze'
from='black'
to='magenta'/>
will make the fill color of path1 transition from black to magenta when the renderer enters state 0.
The gpa:states(...) condition triggers for upcoming state changes
as well, to support fade-out transitions. For example,
<animate href='path1'
attributeName='opacity'
begin='gpa:states(0).end -300ms'
dur='300ms'
fill='freeze'
from='1'
to='0'/>
will start a fade-out of path1 300ms before state 0 ends.
A variant of the gpa:states(...) condition allows specifying
both before and after states:
<animate href='path1'
attributeName='opacity'
begin='gpa:states(0, 1 2)'
dur='300ms'
fill='freeze'
from='1'
to='0'/>
will start the animation when the state changes from 0 to 1 or from 0 to 2, but not when it changes from 0 to 3.
In addition to the gpa:fill and gpa:stroke attributes, symbolic
colors can also be specified as a custom paint server reference,
like this: url(gpa:warning). This works in fill and stroke
attributes, but also when specifying colors in SVG animation
attributes like to or values.
Note that the SVG syntax allows for a fallback RGB color to be specified after the url, for compatibility with other SVG consumers:
fill='url(#gpa:warning) orange'
In contrast to SVG 1.1 and 2.0, we allow the transform attribute
to be animated with <animate>.
- Since:
- 4.22
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classSvg.Builder<B extends Svg.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.static interfaceFunctional interface declaration of theErrorCallbackcallback.static classNested classes/interfaces inherited from class GObject
GObject.NotifyCallback, GObject.ObjectClassNested classes/interfaces inherited from interface Paintable
Paintable.InvalidateContentsCallback, Paintable.InvalidateSizeCallback, Paintable.Paintable$Impl, Paintable.PaintableInterfaceNested classes/interfaces inherited from interface SymbolicPaintable
SymbolicPaintable.SymbolicPaintable$Impl, SymbolicPaintable.SymbolicPaintableInterface -
Constructor Summary
ConstructorsConstructorDescriptionSvg()Create a new Svg.Svg(MemorySegment address) Create a Svg instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionprotected SvgasParent()Return this instance as if it were its parent type.static Svg.Builder<? extends Svg.Builder> builder()ASvg.Builderobject constructs aSvgwith the specified properties.voidEmits the "error" signal.static SvgfromBytes(byte[] bytes) Parses the SVG data inbytesand creates a paintable.static SvgfromResource(String path) Parses the SVG data in the resource and creates a paintable.Returns the currently enabled features.static MemoryLayoutThe memory layout of the native struct.intgetState()Gets the current state of the paintable.@Nullable String @Nullable []getStateNames(Out<Integer> length) Returns aNULL-terminated array of state names, if available.static @Nullable TypegetType()Get the GType of the Svg class.doubleGets the value of the weight property.voidloadFromBytes(byte[] bytes) Loads SVG content into an existing SVG paintable.voidloadFromResource(String path) Loads SVG content into an existing SVG paintable.onError(Svg.ErrorCallback handler) Signals that an error occurred.voidpause()Stop any playing animations and state transitions.voidplay()Start playing animations and state transitions.byte[]Serializes the content of the renderer as SVG.voidsetFeatures(Set<SvgFeatures> features) Enables or disables features of the SVG paintable.voidsetFeatures(SvgFeatures... features) Enables or disables features of the SVG paintable.voidsetFrameClock(FrameClock clock) Sets a frame clock.voidsetState(int state) Sets the state of the paintable.voidsetWeight(double weight) Sets the weight that is used when rendering.booleanwriteToFile(String filename) Serializes the paintable, and saves the result to a file.Methods inherited from class GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newv, notify, notify, notifyByPspec, onNotify, ref, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, unref, watchClosure, weakRef, weakUnref, withPropertiesMethods inherited from class TypeInstance
callParent, callParent, cast, getPrivate, readGClass, writeGClassMethods inherited from class ProxyInstance
equals, handle, hashCodeMethods inherited from class Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface Paintable
computeConcreteSize, emitInvalidateContents, emitInvalidateSize, getCurrentImage, getFlags, getIntrinsicAspectRatio, getIntrinsicHeight, getIntrinsicWidth, invalidateContents, invalidateSize, onInvalidateContents, onInvalidateSize, snapshotMethods inherited from interface SymbolicPaintable
snapshotSymbolic, snapshotWithWeight
-
Constructor Details
-
Svg
Create a Svg instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
Svg
public Svg()Create a new Svg.
-
-
Method Details
-
getType
-
getMemoryLayout
The memory layout of the native struct.- Returns:
- the memory layout
-
asParent
-
fromBytes
Parses the SVG data inbytesand creates a paintable.- Parameters:
bytes- the data- Returns:
- the paintable
- Since:
- 4.22
-
fromResource
-
getFeatures
Returns the currently enabled features.- Returns:
- the enabled features
- Since:
- 4.22
-
getState
public int getState()Gets the current state of the paintable.- Returns:
- the state
- Since:
- 4.22
-
getStateNames
Returns a
NULL-terminated array of state names, if available.Note that the returned array and the strings contained in it will only be valid until the
GtkSvgis cleared or reloaded, so if you want to keep it around, you should make a copy.- Parameters:
length- return location for the number of strings that are returned- Returns:
- the state names
- Since:
- 4.22
-
getWeight
public double getWeight()Gets the value of the weight property.- Returns:
- the weight
- Since:
- 4.22
-
loadFromBytes
public void loadFromBytes(byte[] bytes) Loads SVG content into an existing SVG paintable.
To track errors while loading SVG content, connect to the
Gtk.Svg::errorsignal.This clears any previously loaded content.
- Parameters:
bytes- the data to load- Since:
- 4.22
-
loadFromResource
Loads SVG content into an existing SVG paintable.
To track errors while loading SVG content, connect to the
Gtk.Svg::errorsignal.This clears any previously loaded content.
- Parameters:
path- the resource path- Since:
- 4.22
-
pause
public void pause()Stop any playing animations and state transitions.
Animations can be paused and started repeatedly.
- Since:
- 4.22
-
play
public void play()Start playing animations and state transitions.
Animations can be paused and started repeatedly.
- Since:
- 4.22
-
serialize
public byte[] serialize()Serializes the content of the renderer as SVG.
The SVG will be similar to the orignally loaded one, but is not guaranteed to be 100% identical.
This function serializes the DOM, i.e. the results of parsing the SVG. It does not reflect the effect of applying animations.
- Returns:
- the serialized contents
- Since:
- 4.22
-
setFeatures
Enables or disables features of the SVG paintable.
By default, all features are enabled.
Note that this call only has an effect before the SVG is loaded.
- Parameters:
features- features to enable- Since:
- 4.22
-
setFeatures
Enables or disables features of the SVG paintable.
By default, all features are enabled.
Note that this call only has an effect before the SVG is loaded.
- Parameters:
features- features to enable- Since:
- 4.22
-
setFrameClock
Sets a frame clock.
Without a frame clock, GtkSvg will not advance animations.
- Parameters:
clock- the frame clock- Since:
- 4.22
-
setState
public void setState(int state) Sets the state of the paintable.
If the paintable is currently playing, the state change will apply transitions that are defined in the SVG. If the paintable is not playing, the state change will take effect instantaneously.
- Parameters:
state- the state to set, as a value between 0 and 63- Since:
- 4.22
-
setWeight
public void setWeight(double weight) Sets the weight that is used when rendering.
The weight affects the effective linewidth when stroking paths.
The default value of -1 means to use the font weight from CSS.
- Parameters:
weight- the font weight, as a value between -1 and 1000- Since:
- 4.22
-
writeToFile
Serializes the paintable, and saves the result to a file.- Parameters:
filename- the file to save to- Returns:
- true, unless an error occurred
- Throws:
GErrorException- seeGError- Since:
- 4.22
-
onError
Signals that an error occurred.
Errors can occur both during parsing and during rendering.
The expected error values are in the
Gtk.SvgErrorenumeration, context information about the location of parsing errors can be obtained with the variousgtk_svg_errorfunctions.Parsing errors are never fatal, so the parsing will resume after the error. Errors may however cause parts of the given data or even all of it to not be parsed at all. So it is a useful idea to check that the parsing succeeds by connecting to this signal.
::: note This signal is emitted in the middle of parsing or rendering, and if you handle it, you must be careful. Logging the errors you receive is fine, but modifying the widget hierarchy or changing the paintable state definitively isn't.
If in doubt, defer to an idle.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- Since:
- 4.22
- See Also:
-
emitError
Emits the "error" signal. SeeonError(Svg.ErrorCallback). -
builder
ASvg.Builderobject constructs aSvgwith the specified properties. Use the variousset...()methods to set properties, and finish construction withSvg.Builder.build().- Returns:
- the builder object
-