Geometry¶
Matrices, transform lists, path data and bounding boxes.
Affine matrices and SVG transform lists.
- class MatrixOp(matrix: Matrix)[source]¶
Bases:
TransformOpA literal matrix (
matrix).Wraps a Matrix so it can sit in a transform list.
- Parameters:
matrix (Matrix) – The matrix to apply.
See also
MatrixThe wrapped value.
Examples
>>> from svgwriter.model.transform import MatrixOp >>> from svgwriter.model.transform import Matrix >>> str(MatrixOp(Matrix.scale(2))) 'matrix(2 0 0 2 0 0)'
- class Point(x: float, y: float)[source]¶
Bases:
NamedTupleA 2-D point that is also a vector.
A named tuple, so it unpacks and compares as
(x, y). Arithmetic is element-wise like numpy:+and-take another point or pair,*and/a number or pair;abs(p)is the length.Examples
>>> from svgwriter.model.transform import Point >>> x, y = Point(1, 2) >>> Point(1, 2) == (1, 2) True >>> Point(1, 2) + (3, 4), Point(1, 2) * 2, -Point(1, 2) (Point(x=4.0, y=6.0), Point(x=2.0, y=4.0), Point(x=-1.0, y=-2.0)) >>> abs(Point(3, 4)) 5.0
- class Rotate(angle: float, cx: float = 0.0, cy: float = 0.0)[source]¶
Bases:
TransformOpRotate by an angle, optionally about a centre (
rotate).The centre is omitted when serialized if it is the origin.
- Parameters:
See also
Matrix.rotateThe equivalent matrix.
Examples
>>> from svgwriter.model.transform import Rotate >>> str(Rotate(45, 5, 5)) 'rotate(45 5 5)'
- class Scale(sx: float, sy: float | None = None)[source]¶
Bases:
TransformOpScale about the origin (
scale).With no sy the scaling is uniform.
- Parameters:
See also
Matrix.scaleThe equivalent matrix.
Examples
>>> from svgwriter.model.transform import Scale >>> str(Scale(2)) 'scale(2)'
- class SkewX(angle: float)[source]¶
Bases:
TransformOpSkew along the x axis (
skewX).Shears horizontally by an angle.
- Parameters:
angle (float) – Skew angle in degrees.
See also
SkewYThe vertical counterpart.
Examples
>>> from svgwriter.model.transform import SkewX >>> str(SkewX(30)) 'skewX(30)'
- class SkewY(angle: float)[source]¶
Bases:
TransformOpSkew along the y axis (
skewY).Shears vertically by an angle.
- Parameters:
angle (float) – Skew angle in degrees.
See also
SkewXThe horizontal counterpart.
Examples
>>> from svgwriter.model.transform import SkewY >>> str(SkewY(30)) 'skewY(30)'
- class TransformOp[source]¶
Bases:
ABCOne entry of a
transformlist.Base class of the six SVG transform functions. Each operation knows its keyword and arguments and can be turned into a Matrix.
- Variables:
keyword (str) – The SVG function name, such as
"translate".
See also
TransformA list of operations.
Examples
>>> from svgwriter.model.transform import Translate >>> isinstance(Translate(1), TransformOp) True
- abstract property arguments: tuple[float, ...]¶
The numbers written inside the parentheses.
Examples
>>> from svgwriter.model.transform import Translate >>> Translate(1, 2).arguments (1, 2)
- abstractmethod to_matrix() Matrix[source]¶
Return the matrix equivalent of this operation.
- Returns:
Matrix – The operation as an affine matrix.
Examples
>>> from svgwriter.model.transform import Translate >>> str(Translate(1, 2).to_matrix()) 'translate(1 2)'
- svg_value(precision: int = 4) str[source]¶
Serialize the operation as transform text.
- Parameters:
precision (int, optional) – Maximum number of decimal places. Defaults to the library default precision.
- Returns:
str – The keyword with its arguments, such as
"rotate(45)".
Examples
>>> from svgwriter.model.transform import Scale >>> Scale(1.23456).svg_value(2) 'scale(1.23)'
- class Translate(tx: float, ty: float = 0.0)[source]¶
Bases:
TransformOpMove by an offset (
translate).A frozen dataclass; a zero ty is omitted when serialized.
See also
Matrix.translateThe equivalent matrix.
Examples
>>> from svgwriter.model.transform import Translate >>> str(Translate(10, 5)) 'translate(10 5)'
- as_transform(value: Transform | TransformOp | Matrix | str) Transform[source]¶
Coerce a transform-like value into a Transform.
- Parameters:
value (Transform or TransformOp or Matrix or str) – The value to convert; text is parsed.
- Returns:
Transform – value itself if it is already a Transform, otherwise a new list.
- Raises:
ValueError – If value is text that is not a valid transform list.
See also
parse_transformParse text only.
Examples
>>> from svgwriter.model.transform import Matrix, as_transform >>> str(as_transform("scale(2)")) 'scale(2)' >>> str(as_transform(Matrix.scale(2))) 'matrix(2 0 0 2 0 0)'
- parse_transform(text: str) Transform[source]¶
Parse a
transformattribute value.- Parameters:
text (str) – Transform text such as
"rotate(45) translate(1 2)"; separators may be spaces or commas.- Returns:
Transform – The parsed list of operations.
- Raises:
ValueError – If the text contains anything other than valid transform functions, or a function has the wrong number of arguments.
See also
as_transformAlso accepts matrices and single operations.
Examples
>>> from svgwriter.model.transform import parse_transform >>> str(parse_transform("rotate(45, 1, 2) skewX(3)")) 'rotate(45 1 2) skewX(3)'
- class Matrix(a: float = 1.0, b: float = 0.0, c: float = 0.0, d: float = 1.0, e: float = 0.0, f: float = 0.0)[source]¶
Bases:
MatrixConstructors,MatrixText,DrawableAn affine transform
[a c e; b d f; 0 0 1].Matrices compose with
@in SVG order:m1 @ m2appliesm2first, matchingtransform="m1 m2". Instances are immutable.- Parameters:
a (float, optional) – The six SVG matrix entries;
eandfare the translation. Default to the identity (1, 0, 0, 1, 0, 0).b (float, optional) – The six SVG matrix entries;
eandfare the translation. Default to the identity (1, 0, 0, 1, 0, 0).c (float, optional) – The six SVG matrix entries;
eandfare the translation. Default to the identity (1, 0, 0, 1, 0, 0).d (float, optional) – The six SVG matrix entries;
eandfare the translation. Default to the identity (1, 0, 0, 1, 0, 0).e (float, optional) – The six SVG matrix entries;
eandfare the translation. Default to the identity (1, 0, 0, 1, 0, 0).f (float, optional) – The six SVG matrix entries;
eandfare the translation. Default to the identity (1, 0, 0, 1, 0, 0).
See also
TransformAn ordered list of transform operations.
Examples
>>> from svgwriter.model.transform import Matrix >>> (Matrix.translate(10, 0) @ Matrix.scale(2)).apply(1, 1) Point(x=12.0, y=2.0) >>> Matrix.scale(3) @ (1, 2) Point(x=3.0, y=6.0)
- property determinant: float¶
The determinant
a*d - b*c; negative when the transform mirrors.Examples
>>> from svgwriter.model.transform import Matrix >>> Matrix.scale(2, 3).determinant 6.0
- property is_identity: bool¶
Whether the matrix equals the identity within tolerance.
Examples
>>> from svgwriter.model.transform import Matrix >>> Matrix().is_identity True >>> Matrix.translate(1).is_identity False
- inverse() Matrix[source]¶
Return the inverse transform.
- Returns:
Matrix – The matrix that undoes this one.
- Raises:
ValueError – If the matrix is singular.
Examples
>>> from svgwriter.model.transform import Matrix >>> str(Matrix.translate(5, 0).inverse()) 'translate(-5)'
- apply(x: float, y: float) Point[source]¶
Map a single point.
- Parameters:
- Returns:
Point – The transformed point.
See also
apply_pointsVectorized version.
Examples
>>> from svgwriter.model.transform import Matrix >>> Matrix.translate(1, 2).apply(1, 1) Point(x=2.0, y=3.0)
- apply_points(points: ndarray) ndarray[source]¶
Map an
(..., 2)array of points in one vectorized step.- Parameters:
points (numpy.ndarray) – Array whose last axis holds
x, ypairs.- Returns:
numpy.ndarray – Float array of the same shape with every point mapped.
- Raises:
ValueError – If the last axis does not have length 2.
See also
applyMap a single point.
Examples
>>> import numpy as np >>> from svgwriter.model.transform import Matrix >>> Matrix.translate(1, 2) @ np.array([[0, 0], [1, 1]]) array([[1., 2.], [2., 3.]])
- classmethod from_array(array: object) Matrix[source]¶
Build a matrix from a 3x3 (or 2x3) array.
- Parameters:
array (array_like) – Array in
[[a, c, e], [b, d, f]]layout; a third row is ignored.- Returns:
Matrix – The matrix with those entries.
- Raises:
ValueError – If the array is not 2x3 or 3x3.
Examples
>>> from svgwriter.model.transform import Matrix >>> str(Matrix.from_array([[1, 0, 5], [0, 1, 6]])) 'translate(5 6)'
- as_tuple() tuple[float, float, float, float, float, float][source]¶
Return the entries as
(a, b, c, d, e, f).- Returns:
tuple of float – The six matrix entries in SVG
matrix()order.
Examples
>>> from svgwriter.model.transform import Matrix >>> Matrix.translate(5, 6).as_tuple() (1.0, 0.0, 0.0, 1.0, 5, 6)
- isclose(other: Matrix | object, tolerance: float = 1e-09) bool[source]¶
Return whether another transform is equal within a tolerance.
- Parameters:
- Returns:
bool – True if every entry is within tolerance.
Examples
>>> from svgwriter.model.transform import Matrix >>> Matrix.rotate(90).isclose("rotate(90)") True
- decompose() tuple[float, float, float, float, float, float][source]¶
Decompose into translation, rotation, skew and scale.
The parts satisfy
M = translate rotate skewX scale.- Returns:
tuple of float –
(tx, ty, angle, skew_x, sx, sy); angles are in degrees.
Examples
>>> from svgwriter.model.transform import Matrix >>> (Matrix.translate(10, 5) @ Matrix.scale(2)).decompose() (10.0, 5.0, 0.0, 0.0, 2.0, 2.0)
- classmethod flip_x(x: float = 0.0) Matrix¶
Return a mirror across a vertical line.
- Parameters:
x (float, optional) – The x coordinate of the mirror line. Defaults to 0.
- Returns:
Matrix – The reflection matrix.
See also
flip_yMirror across a horizontal line.
Examples
>>> from svgwriter.model.transform import Matrix >>> Matrix.flip_x(5).apply(1, 1) Point(x=9.0, y=1.0)
- classmethod flip_y(y: float = 0.0) Matrix¶
Return a mirror across a horizontal line.
- Parameters:
y (float, optional) – The y coordinate of the mirror line. Defaults to 0.
- Returns:
Matrix – The reflection matrix.
See also
flip_xMirror across a vertical line.
Examples
>>> from svgwriter.model.transform import Matrix >>> Matrix.flip_y(5).apply(1, 1) Point(x=1.0, y=9.0)
- classmethod rotate(angle: float, cx: float = 0.0, cy: float = 0.0) Matrix¶
Return a rotation, optionally about a centre.
- Parameters:
- Returns:
Matrix – The rotation matrix.
Examples
>>> from svgwriter.model.transform import Matrix >>> p = Matrix.rotate(90, 5, 5).apply(10, 5) >>> round(p.x, 6), round(p.y, 6) (5.0, 10.0)
- classmethod scale(sx: float, sy: float | None = None) Matrix¶
Return a scaling about the origin.
- Parameters:
- Returns:
Matrix – The scaling matrix.
Examples
>>> from svgwriter.model.transform import Matrix >>> Matrix.scale(2, 3).apply(1, 1) Point(x=2.0, y=3.0)
- classmethod skew_x(angle: float) Matrix¶
Return a horizontal skew.
- Parameters:
angle (float) – Skew angle in degrees along the x axis.
- Returns:
Matrix – The skew matrix.
See also
skew_yVertical skew.
Examples
>>> from svgwriter.model.transform import Matrix >>> str(Matrix.skew_x(30)) 'skewX(30)'
- classmethod skew_y(angle: float) Matrix¶
Return a vertical skew.
- Parameters:
angle (float) – Skew angle in degrees along the y axis.
- Returns:
Matrix – The skew matrix.
See also
skew_xHorizontal skew.
Examples
>>> from svgwriter.model.transform import Matrix >>> Matrix.skew_y(45).isclose(Matrix(1, 1, 0, 1, 0, 0)) True
- svg_value(precision: int = 4, *, anchor: tuple[float, float] | None = None, box: Any = None) str¶
The shortest
transformtext for this matrix.Rigid motions become
rotate(a cx cy); otherwise the parts oftranslate rotate skewX scalethat are not identity, falling back tomatrix(...)when that is shorter.- Parameters:
precision (int, optional) – Maximum number of decimal places. Defaults to the library default precision.
anchor ((float, float), optional) – The element’s anchor. When a pure rotation’s centre would fall outside box, the text becomes
translate(dx dy) rotate(a px py)about this point instead, which is what a person would write. Defaults to None.box (BBox, optional) – The element’s local bounding box, used with anchor. Defaults to None.
- Returns:
str – Text suitable for a
transformattribute; empty for the identity.
Examples
>>> from svgwriter.model.transform import Matrix >>> Matrix.rotate(90, 5, 5).svg_value() 'rotate(90 5 5)' >>> (Matrix.translate(10, 5) @ Matrix.scale(2, 3)).svg_value() 'matrix(2 0 0 3 10 5)' >>> Matrix.skew_x(30).svg_value() 'skewX(30)'
- class Transform(ops: Iterable[TransformOp] = ())[source]¶
Bases:
TransformBuildersAn ordered list of transform operations.
Builder methods append and return
self; called on the class they start a new list.@concatenates in SVG order (the right operand is applied first) and also accepts single operations and matrices.- Parameters:
ops (iterable of TransformOp, optional) – Initial operations. Defaults to an empty list.
See also
MatrixA single affine matrix.
parse_transformBuild from
transformattribute text.
Examples
>>> from svgwriter.model.transform import Transform >>> str(Transform().translate(10, 20).rotate(45)) 'translate(10 20) rotate(45)' >>> str(Transform.rotate(30) @ Transform.scale(2)) 'rotate(30) scale(2)' >>> Transform.translate(5) @ (1, 1) Point(x=6.0, y=1.0)
- classmethod parse(text: str) Transform[source]¶
Parse a
transformattribute value.- Parameters:
text (str) – Transform text such as
"translate(5) scale(2)".- Returns:
Transform – The parsed list.
- Raises:
ValueError – If the text is not a valid transform list.
See also
parse_transformThe equivalent function.
Examples
>>> from svgwriter.model.transform import Transform >>> str(Transform.parse("translate(5) scale(2)")) 'translate(5) scale(2)'
- to_matrix() Matrix[source]¶
Collapse the list into a single matrix.
- Returns:
Matrix – The product of every operation, in SVG order.
Examples
>>> from svgwriter.model.transform import Transform >>> str(Transform().translate(10, 0).scale(2).to_matrix()) 'matrix(2 0 0 2 10 0)'
- apply(x: float, y: float) Point[source]¶
Map a single point through the whole list.
- Parameters:
- Returns:
Point – The transformed point.
Examples
>>> from svgwriter.model.transform import Transform >>> Transform().translate(10, 0).scale(2).apply(1, 1) Point(x=12.0, y=2.0)
- simplified() Transform[source]¶
Return an equivalent single
matrix(...)transform.- Returns:
Transform – A one-operation list with the same effect.
Examples
>>> from svgwriter.model.transform import Transform >>> str(Transform().translate(10, 0).scale(2).simplified()) 'matrix(2 0 0 2 10 0)'
- inverse() Transform[source]¶
Return the inverse as a single
matrix(...).- Returns:
Transform – A one-operation list that undoes this one.
- Raises:
ValueError – If the transform is singular.
Examples
>>> from svgwriter.model.transform import Transform >>> str(Transform().translate(5, 0).inverse()) 'matrix(1 0 0 1 -5 0)'
- svg_value(precision: int = 4) str[source]¶
Serialize the list as
transformattribute text.- Parameters:
precision (int, optional) – Maximum number of decimal places. Defaults to the library default precision.
- Returns:
str – Space-separated operations; empty for an empty list.
Examples
>>> from svgwriter.model.transform import Transform >>> Transform().translate(1.23456, 0).rotate(45).svg_value(2) 'translate(1.23) rotate(45)'
- matrix(a: float, b: float, c: float, d: float, e: float, f: float) None¶
Append a literal matrix.
- Parameters:
- Returns:
Transform – This list (or a new one when called on the class), for chaining.
Examples
>>> from svgwriter.model.transform import Transform >>> str(Transform.matrix(1, 0, 0, 1, 5, 6)) 'matrix(1 0 0 1 5 6)'
- rotate(angle: float, cx: float = 0.0, cy: float = 0.0) None¶
Append a rotation.
- Parameters:
- Returns:
Transform – This list (or a new one when called on the class), for chaining.
Examples
>>> from svgwriter.model.transform import Transform >>> str(Transform.rotate(45, 5, 5)) 'rotate(45 5 5)'
- scale(sx: float, sy: float | None = None) None¶
Append a scaling.
- Parameters:
- Returns:
Transform – This list (or a new one when called on the class), for chaining.
Examples
>>> from svgwriter.model.transform import Transform >>> str(Transform().scale(2, 3)) 'scale(2 3)'
- skew_x(angle: float) None¶
Append a horizontal skew.
- Parameters:
angle (float) – Skew angle in degrees.
- Returns:
Transform – This list (or a new one when called on the class), for chaining.
Examples
>>> from svgwriter.model.transform import Transform >>> str(Transform.skew_x(30)) 'skewX(30)'
- skew_y(angle: float) None¶
Append a vertical skew.
- Parameters:
angle (float) – Skew angle in degrees.
- Returns:
Transform – This list (or a new one when called on the class), for chaining.
Examples
>>> from svgwriter.model.transform import Transform >>> str(Transform.skew_y(30)) 'skewY(30)'
Path data: commands, parsing, serialization, arcs and a builder.
- class ArcTo(rx: float, ry: float, rotation: float, large_arc: bool, sweep: bool, x: float, y: float, *, relative: bool = False)[source]¶
Bases:
XYEnd,PathCommandElliptical arc (
A/a).The two flags select one of the four candidate arcs through the endpoints.
- Parameters:
rx (float) – Ellipse radii.
ry (float) – Ellipse radii.
rotation (float) – Rotation of the ellipse’s x axis, in degrees.
large_arc (bool) – Choose the arc spanning more than half the ellipse.
sweep (bool) – Choose the clockwise (positive-angle) direction.
x (float) – End point (offsets when relative).
y (float) – End point (offsets when relative).
relative (bool, optional) – Use the lowercase (relative) form; keyword-only. Defaults to False.
See also
svgwriter.model.pathdata.endpoint_to_centerConvert to center parameterization.
Examples
>>> from svgwriter.model.pathdata import ArcTo >>> str(ArcTo(5, 5, 0, False, True, 10, 0)) 'A5 5 0 0 1 10 0'
- class BBox(x: float, y: float, width: float, height: float)[source]¶
Bases:
NamedTupleAxis-aligned bounding box.
A named tuple, so it unpacks as
x, y, width, height.- Parameters:
See also
PathData.bboxThe bounding box of path data.
Examples
>>> from svgwriter.model.pathdata import BBox >>> x, y, w, h = BBox(1, 2, 3, 4) >>> w, h (3, 4)
- classmethod from_points(points: Iterable[Point | tuple[float, float]]) BBox[source]¶
Return the smallest box containing every point.
- Parameters:
points (iterable of Point or tuple of float) – The points to enclose.
- Returns:
BBox – The enclosing box; an empty input gives a zero box at the origin.
Examples
>>> from svgwriter.model.pathdata import BBox >>> BBox.from_points([(0, 0), (4, 2)]) BBox(x=0, y=0, width=4, height=2)
- property center: Point¶
The centre of the box.
Examples
>>> from svgwriter.model.pathdata import BBox >>> BBox(0, 0, 4, 2).center Point(x=2.0, y=1.0)
- property top_left¶
Corner at
(left, top).
- property top_center¶
Middle of the top edge.
- property top_right¶
Corner at
(right, top).
- property center_left¶
Middle of the left edge.
- property center_right¶
Middle of the right edge.
- property bottom_left¶
Corner at
(left, bottom).
- property bottom_center¶
Middle of the bottom edge.
- property bottom_right¶
Corner at
(right, bottom).
- static point_names() tuple[str, ...][source]¶
The names
point()accepts.- Returns:
tuple of str – Centre, corners, edge middles and edge names.
Examples
>>> from svgwriter.model.pathdata import BBox >>> BBox.point_names()[:3] ('center', 'top_left', 'top_center')
- point(name: str) Point[source]¶
A named point of the box.
- Parameters:
name (str) –
"center", a corner ("top_left","top_right","bottom_left","bottom_right"), an edge middle ("top_center","center_left", …), or an edge name ("top","left", …) meaning that edge’s middle.- Returns:
Point – The point in the box’s coordinates.
- Raises:
ValueError – If the name is unknown.
Examples
>>> from svgwriter.model.pathdata import BBox >>> box = BBox(0, 0, 4, 2) >>> box.point("top_right"), box.point("bottom"), box.bottom_left (Point(x=4.0, y=0.0), Point(x=2.0, y=2.0), Point(x=0.0, y=2.0))
- union(other: BBox) BBox[source]¶
Return the smallest box containing this box and another.
- Parameters:
other (BBox) – The box to merge with.
- Returns:
BBox – The combined box.
Examples
>>> from svgwriter.model.pathdata import BBox >>> BBox(0, 0, 4, 2).union(BBox(10, 10, 1, 1)) BBox(x=0, y=0, width=11, height=11)
- class CenterArc(cx: float, cy: float, rx: float, ry: float, rotation: float, start_angle: float, sweep: float)[source]¶
Bases:
objectAn elliptical arc in center parameterization.
Describes the arc by the ellipse centre, radii and rotation plus a start angle and a signed sweep, which is easier to sample than the endpoint form.
- Parameters:
cx (float) – Centre of the ellipse.
cy (float) – Centre of the ellipse.
rx (float) – Radii of the ellipse along its own axes.
ry (float) – Radii of the ellipse along its own axes.
rotation (float) – Rotation of the ellipse’s x axis, in degrees.
start_angle (float) – Angle of the arc’s first point on the ellipse, in radians.
sweep (float) – Signed angular extent in radians; positive is clockwise in SVG’s y-down coordinate system.
See also
endpoint_to_centerBuild a CenterArc from SVG endpoint parameters.
Examples
>>> from svgwriter.model.pathdata import CenterArc >>> arc = CenterArc(0, 0, 5, 5, 0, 0.0, 3.141592653589793) >>> arc.sweep > 0 True
- point_at(t: float) Point[source]¶
Return the point at parameter t along the arc.
- Parameters:
t (float) – Position along the arc, from 0 (start) to 1 (end).
- Returns:
Point – The point on the arc.
Examples
>>> from svgwriter.model.pathdata import endpoint_to_center >>> from svgwriter.model.transform import Point >>> arc = endpoint_to_center(Point(0, 0), Point(10, 0), 5, 5, 0, False, True) >>> p = arc.point_at(0.5) >>> round(p.x, 6), round(p.y, 6) (5.0, -5.0)
- sample(count: int) list[Point][source]¶
Return evenly spaced points along the arc.
- Parameters:
count (int) – Number of segments; the result has
count + 1points including both ends.- Returns:
list of Point – Points from the start to the end of the arc.
Examples
>>> from svgwriter.model.pathdata import endpoint_to_center >>> from svgwriter.model.transform import Point >>> arc = endpoint_to_center(Point(0, 0), Point(10, 0), 5, 5, 0, False, True) >>> len(arc.sample(4)) 5
- class ClosePath(*, relative: bool = False)[source]¶
Bases:
PathCommandClose the current subpath (
Z/z).Draws a straight line back to the subpath’s start and returns the pen there.
- Parameters:
relative (bool, optional) – Use the lowercase form; keyword-only and equivalent to the uppercase one. Defaults to False.
Examples
>>> from svgwriter.model.pathdata import ClosePath >>> str(ClosePath()) 'Z'
- property arguments: tuple[float, ...]¶
Numbers written after the command letter, in order.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> LineTo(1, 2).arguments (1.0, 2.0)
- end_point(current: Point, start: Point) Point[source]¶
Return the absolute pen position after this segment.
- Parameters:
- Returns:
Point – The pen position once the command has been drawn.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> from svgwriter.model.transform import Point >>> LineTo(1, 2, relative=True).end_point(Point(10, 10), Point(0, 0)) Point(x=11, y=12)
- class CurveTo(x1: float, y1: float, x2: float, y2: float, x: float, y: float, *, relative: bool = False)[source]¶
Bases:
XYEnd,PathCommandCubic Bezier with two explicit control points (
C/c).- Parameters:
See also
SmoothCurveToCubic curve with a reflected first control point.
Examples
>>> from svgwriter.model.pathdata import CurveTo >>> str(CurveTo(1, 2, 3, 4, 5, 6)) 'C1 2 3 4 5 6'
- class HLineTo(x: float, *, relative: bool = False)[source]¶
Bases:
PathCommandDraw a horizontal line (
H/h).Draws to a new x coordinate, keeping y.
- Parameters:
See also
VLineToThe vertical counterpart.
Examples
>>> from svgwriter.model.pathdata import HLineTo >>> str(HLineTo(5)) 'H5'
- property arguments: tuple[float, ...]¶
Numbers written after the command letter, in order.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> LineTo(1, 2).arguments (1.0, 2.0)
- end_point(current: Point, start: Point) Point[source]¶
Return the absolute pen position after this segment.
- Parameters:
- Returns:
Point – The pen position once the command has been drawn.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> from svgwriter.model.transform import Point >>> LineTo(1, 2, relative=True).end_point(Point(10, 10), Point(0, 0)) Point(x=11, y=12)
- class LineTo(x: float, y: float, *, relative: bool = False)[source]¶
Bases:
XYEnd,PathCommandDraw a straight line (
L/l).Draws from the current point to the given point.
- Parameters:
See also
MoveToMove without drawing.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> str(LineTo(1, 2, relative=True)) 'l1 2'
- class MoveTo(x: float, y: float, *, relative: bool = False)[source]¶
Bases:
XYEnd,PathCommandMove the pen without drawing (
M/m).Starts a new subpath at the given point.
- Parameters:
See also
LineToDraw to a point.
Examples
>>> from svgwriter.model.pathdata import MoveTo >>> str(MoveTo(1, 2)) 'M1 2'
- class QuadTo(x1: float, y1: float, x: float, y: float, *, relative: bool = False)[source]¶
Bases:
XYEnd,PathCommandQuadratic Bezier curve (
Q/q).A curve with a single explicit control point.
- Parameters:
See also
SmoothQuadToQuadratic curve with a reflected control point.
Examples
>>> from svgwriter.model.pathdata import QuadTo >>> str(QuadTo(1, 2, 3, 4)) 'Q1 2 3 4'
- class SmoothCurveTo(x2: float, y2: float, x: float, y: float, *, relative: bool = False)[source]¶
Bases:
XYEnd,PathCommandCubic Bezier whose first control point is reflected (
S/s).- Parameters:
See also
CurveToCubic curve with two explicit control points.
Examples
>>> from svgwriter.model.pathdata import SmoothCurveTo >>> str(SmoothCurveTo(3, 4, 5, 6)) 'S3 4 5 6'
- class SmoothQuadTo(x: float, y: float, *, relative: bool = False)[source]¶
Bases:
XYEnd,PathCommandQuadratic Bezier with a reflected control point (
T/t).The control point is the reflection of the previous quadratic curve’s control point.
- Parameters:
See also
QuadToQuadratic curve with an explicit control point.
Examples
>>> from svgwriter.model.pathdata import SmoothQuadTo >>> str(SmoothQuadTo(3, 4)) 'T3 4'
- class VLineTo(y: float, *, relative: bool = False)[source]¶
Bases:
PathCommandDraw a vertical line (
V/v).Draws to a new y coordinate, keeping x.
- Parameters:
See also
HLineToThe horizontal counterpart.
Examples
>>> from svgwriter.model.pathdata import VLineTo >>> str(VLineTo(5, relative=True)) 'v5'
- property arguments: tuple[float, ...]¶
Numbers written after the command letter, in order.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> LineTo(1, 2).arguments (1.0, 2.0)
- end_point(current: Point, start: Point) Point[source]¶
Return the absolute pen position after this segment.
- Parameters:
- Returns:
Point – The pen position once the command has been drawn.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> from svgwriter.model.transform import Point >>> LineTo(1, 2, relative=True).end_point(Point(10, 10), Point(0, 0)) Point(x=11, y=12)
- endpoint_to_center(start: Point, end: Point, rx: float, ry: float, rotation: float, large_arc: bool, sweep: bool) CenterArc | None[source]¶
Convert endpoint arc parameters to a CenterArc.
Implements the conversion from SVG 1.1 appendix F.6.5. Radii that are too small to span the endpoints are scaled up as the specification requires.
- Parameters:
start (Point) – The arc’s start and end points.
end (Point) – The arc’s start and end points.
rx (float) – Ellipse radii.
ry (float) – Ellipse radii.
rotation (float) – Rotation of the ellipse’s x axis, in degrees.
large_arc (bool) – Choose the arc spanning more than half the ellipse.
sweep (bool) – Choose the arc drawn in the positive-angle (clockwise) direction.
- Returns:
CenterArc or None – The centre form, or
Nonewhen the arc degenerates to a straight line (zero radius or coincident endpoints).
See also
CenterArcThe returned parameterization.
Examples
>>> from svgwriter.model.pathdata import endpoint_to_center >>> from svgwriter.model.transform import Point >>> arc = endpoint_to_center(Point(0, 0), Point(10, 0), 5, 5, 0, False, True) >>> arc.cx, arc.cy (5.0, 0.0) >>> endpoint_to_center(Point(0, 0), Point(0, 0), 5, 5, 0, False, True) is None True
- iter_commands(text: str) Iterator[PathCommand][source]¶
Iterate the commands of path data text, expanding implicit repeats.
M0 0 1 1yields aMoveTofollowed by aLineTo; a repeatedmovetobecomes alinetoof the same case. Empty text yields nothing.- Parameters:
text (str) – Path data, as in the
dattribute.- Yields:
PathCommand – The commands in order.
- Raises:
PathSyntaxError – If the text is malformed or does not start with a moveto.
See also
parse_pathThe same, collected into a list.
Examples
>>> from svgwriter.model.pathdata import iter_commands >>> [str(c) for c in iter_commands("M0 0 1 1 l2 2")] ['M0 0', 'L1 1', 'l2 2']
- parse_path(text: str) list[PathCommand][source]¶
Parse path data text into a list of commands.
- Parameters:
text (str) – Path data, as in the
dattribute.- Returns:
list of PathCommand – The parsed commands.
- Raises:
PathSyntaxError – If the text is malformed or does not start with a moveto.
See also
iter_commandsLazy version.
Examples
>>> from svgwriter.model.pathdata import parse_path >>> [str(c) for c in parse_path("M0 0 L1 1 z")] ['M0 0', 'L1 1', 'z']
- class PathBuilder(start: tuple[float, float] | None = None)[source]¶
Bases:
CurveCommands,ShapeCommandsAccumulate path commands with chained method calls.
Every drawing method returns the builder and accepts
relative=Trueto emit the lowercase form of the command. The builder tracks the current point, so relative commands and closing behave as in SVG.- Parameters:
start (tuple of float, optional) – If given, a
movetoto this point is issued immediately. Defaults to None.
See also
PathDataThe immutable result of build.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> d = PathBuilder().move_to(0, 0).line_to(10, 0).arc_to(5, 5, 0, False, True, 10, 10).close() >>> str(d.build()) 'M0 0 L10 0 A5 5 0 0 1 10 10 Z'
- property current_point: Point¶
The pen position after the most recent command.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> PathBuilder((1, 2)).line_to(5, 5, relative=True).current_point Point(x=6, y=7)
- move_to(x: float, y: float, *, relative: bool = False) None[source]¶
Start a new subpath at a point.
Lifts the pen and moves it without drawing.
- Parameters:
- Returns:
PathBuilder – The builder itself, for chaining.
See also
line_toDraw to a point instead of moving.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(1, 2)) 'M1 2'
- line_to(x: float, y: float, *, relative: bool = False) None[source]¶
Draw a straight line to a point.
Appends an
L(orl) command.- Parameters:
- Returns:
PathBuilder – The builder itself, for chaining.
See also
horizontal_toAxis-aligned line along x.
vertical_toAxis-aligned line along y.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).line_to(10, 5)) 'M0 0 L10 5'
- horizontal_to(x: float, *, relative: bool = False) None[source]¶
Draw a horizontal line.
Appends an
H(orh) command; the y coordinate is unchanged.- Parameters:
- Returns:
PathBuilder – The builder itself, for chaining.
See also
line_toDraw to an arbitrary point.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).horizontal_to(10)) 'M0 0 H10'
- vertical_to(y: float, *, relative: bool = False) None[source]¶
Draw a vertical line.
Appends a
V(orv) command; the x coordinate is unchanged.- Parameters:
- Returns:
PathBuilder – The builder itself, for chaining.
See also
line_toDraw to an arbitrary point.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).vertical_to(10, relative=True)) 'M0 0 v10'
- close() None[source]¶
Close the current subpath.
Appends a
Zcommand and returns the pen to the subpath’s start.- Returns:
PathBuilder – The builder itself, for chaining.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).line_to(5, 0).close()) 'M0 0 L5 0 Z'
- build() PathData[source]¶
Return the accumulated commands as immutable path data.
- Returns:
PathData – A snapshot; later builder calls do not affect it.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> PathBuilder().move_to(0, 0).horizontal_to(5).build() PathData('M0 0 H5')
- to_element(**kwargs: Any) Path[source]¶
Wrap the data in a
<path>element.- Parameters:
**kwargs – Passed to svgwriter.model.elements.shapes.Path (attributes such as
fill).- Returns:
Path – A path element holding the built data.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).to_element(fill="red")) '<path d="M0 0" fill="red"/>'
- arc_to(rx: float, ry: float, rotation: float, large_arc: bool, sweep: bool, x: float, y: float, *, relative: bool = False) None¶
Draw an elliptical arc.
Appends an
A(ora) command; the flags choose one of the four arcs through the endpoints.- Parameters:
rx (float) – Ellipse radii.
ry (float) – Ellipse radii.
rotation (float) – Rotation of the ellipse’s x axis, in degrees.
large_arc (bool) – Choose the arc spanning more than half the ellipse.
sweep (bool) – Choose the clockwise (positive-angle) direction.
x (float) – End point of the arc.
y (float) – End point of the arc.
relative (bool, optional) – Emit the lowercase (relative) form of the command. Defaults to False.
- Returns:
PathBuilder – The builder itself, for chaining.
See also
circleAppend a full circle.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).arc_to(5, 5, 0, False, True, 10, 0)) 'M0 0 A5 5 0 0 1 10 0'
- circle(cx: float, cy: float, r: float) Self¶
Append a full circle as two half arcs.
The subpath starts at the leftmost point and is closed.
- Parameters:
- Returns:
PathBuilder – The builder itself, for chaining.
See also
regular_polygonAppend a closed polygon.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().circle(5, 5, 5)) 'M0 5 A5 5 0 0 1 10 5 A5 5 0 0 1 0 5 Z'
- curve_to(x1: float, y1: float, x2: float, y2: float, x: float, y: float, *, relative: bool = False) None¶
Draw a cubic Bezier curve.
Appends a
C(orc) command with two explicit control points.- Parameters:
x1 (float) – First control point.
y1 (float) – First control point.
x2 (float) – Second control point.
y2 (float) – Second control point.
x (float) – End point of the curve.
y (float) – End point of the curve.
relative (bool, optional) – Emit the lowercase (relative) form of the command. Defaults to False.
- Returns:
PathBuilder – The builder itself, for chaining.
See also
smooth_curve_toCubic curve with a reflected first control point.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).curve_to(1, 1, 2, 1, 3, 0)) 'M0 0 C1 1 2 1 3 0'
- extend(data: PathData | str) Self¶
Append existing path data.
Every command of data is pushed in order, so the current point follows it.
- Parameters:
data (PathData or str) – Commands to append; text is parsed and must begin with a
moveto.- Returns:
PathBuilder – The builder itself, for chaining.
- Raises:
PathSyntaxError – If data is text that is not valid path data.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).extend("M5 5 l1 1")) 'M0 0 M5 5 l1 1'
- quad_to(x1: float, y1: float, x: float, y: float, *, relative: bool = False) None¶
Draw a quadratic Bezier curve.
Appends a
Q(orq) command.- Parameters:
- Returns:
PathBuilder – The builder itself, for chaining.
See also
smooth_quad_toQuadratic curve with a reflected control point.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).quad_to(5, 5, 10, 0)) 'M0 0 Q5 5 10 0'
- regular_polygon(cx: float, cy: float, radius: float, sides: int, rotation: float = -90.0) Self¶
Append a closed regular polygon.
Vertices are spaced evenly on a circle; the first vertex points up by default.
- Parameters:
cx (float) – Centre of the polygon.
cy (float) – Centre of the polygon.
radius (float) – Distance from the centre to each vertex.
sides (int) – Number of sides; at least 3.
rotation (float, optional) – Angle of the first vertex in degrees, measured clockwise from the positive x axis. Defaults to -90 (pointing up).
- Returns:
PathBuilder – The builder itself, for chaining.
- Raises:
ValueError – If sides is less than 3.
See also
circleAppend a full circle.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().regular_polygon(0, 0, 10, 3)) 'M0 -10 L8.6603 5 L-8.6603 5 Z'
- smooth_curve_to(x2: float, y2: float, x: float, y: float, *, relative: bool = False) None¶
Draw a smooth cubic Bezier curve.
Appends an
S(ors) command; the first control point is the reflection of the previous curve’s second.- Parameters:
- Returns:
PathBuilder – The builder itself, for chaining.
See also
curve_toCubic curve with explicit control points.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).curve_to(1, 1, 2, 1, 3, 0).smooth_curve_to(5, -1, 6, 0)) 'M0 0 C1 1 2 1 3 0 S5 -1 6 0'
- smooth_quad_to(x: float, y: float, *, relative: bool = False) None¶
Draw a smooth quadratic Bezier curve.
Appends a
T(ort) command; the control point is the reflection of the previous one.- Parameters:
- Returns:
PathBuilder – The builder itself, for chaining.
See also
quad_toQuadratic curve with an explicit control point.
Examples
>>> from svgwriter.model.pathdata import PathBuilder >>> str(PathBuilder().move_to(0, 0).quad_to(5, 5, 10, 0).smooth_quad_to(20, 0)) 'M0 0 Q5 5 10 0 T20 0'
- class PathCommand[source]¶
Bases:
CommandForms,ABCOne segment of path data.
Base class of the ten SVG path commands. Each command knows its letter, its numeric arguments and where it leaves the pen, and can be converted from relative to absolute form.
- Variables:
See also
PathDataA sequence of commands.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> isinstance(LineTo(1, 2), PathCommand) True
- abstract property arguments: tuple[float, ...]¶
Numbers written after the command letter, in order.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> LineTo(1, 2).arguments (1.0, 2.0)
- abstractmethod end_point(current: Point, start: Point) Point[source]¶
Return the absolute pen position after this segment.
- Parameters:
- Returns:
Point – The pen position once the command has been drawn.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> from svgwriter.model.transform import Point >>> LineTo(1, 2, relative=True).end_point(Point(10, 10), Point(0, 0)) Point(x=11, y=12)
- property letter: str¶
uppercase, or lowercase when relative.
Examples
>>> from svgwriter.model.pathdata import MoveTo >>> MoveTo(1, 2, relative=True).letter 'm'
- Type:
The command letter as written
- svg_value(precision: int = 4) str¶
Serialize the command as path data text.
- Parameters:
precision (int, optional) – Maximum number of decimal places. Defaults to the library default precision.
- Returns:
str – The command letter followed by its arguments.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> LineTo(1.23456, 2).svg_value(2) 'L1.23 2'
- to_absolute(current: Point) Self¶
Return an absolute equivalent of the command.
- Parameters:
current (Point) – Pen position before the command; relative coordinates are offsets from it.
- Returns:
PathCommand – The command itself if already absolute, otherwise a new one.
Examples
>>> from svgwriter.model.pathdata import LineTo >>> from svgwriter.model.transform import Point >>> LineTo(1, 2, relative=True).to_absolute(Point(10, 10)) LineTo(x=11, y=12, relative=False)
- class PathData(commands: str | Iterable[PathCommand] = ())[source]¶
Bases:
PathGeometry,Drawable,Sequence[PathCommand]A parsed, immutable sequence of path commands.
Supports indexing, slicing, iteration, concatenation with
+and transformation with@. Instances are hashable and compare by their commands.- Parameters:
commands (str or iterable of PathCommand, optional) – Path data text, or commands. Defaults to an empty path.
- Raises:
PathSyntaxError – If commands is text that is not valid path data.
See also
PathBuilderFluent construction of path data.
Examples
>>> from svgwriter.model.pathdata import PathData >>> from svgwriter.model.transform import Matrix >>> d = PathData("M0 0 h10 v10 z") >>> str(d.to_absolute()) 'M0 0 H10 V10 Z' >>> d.bbox BBox(x=0.0, y=0.0, width=10.0, height=10.0) >>> str(Matrix.translate(5, 0) @ d) 'M5 0 L15 0 L15 10 Z' >>> len((d + "M20 20 h5").subpaths()) 2
- property bbox: BBox | None[source]¶
Approximate bounding box, or
Nonefor empty data.Computed from sampled outline points, so curves are approximate.
- Returns:
BBox or None – The box around the sampled points, or
Nonewhen there are none.
Examples
>>> from svgwriter.model.pathdata import PathData >>> PathData("M0 0 L10 0 L10 10").bbox BBox(x=0.0, y=0.0, width=10.0, height=10.0) >>> PathData().bbox is None True
- count(value) integer -- return number of occurrences of value¶
- index(value[, start[, stop]]) integer -- return first index of¶
value. Raises ValueError if the value is not present.
Supporting start and stop arguments is optional, but recommended.
- nodes() ndarray¶
Every coordinate pair (end points and control points) as an
(N, 2)array.Coordinates are absolute;
H/Vcount as points on their line. Arc radii and flags are not nodes.- Returns:
numpy.ndarray – Array of shape
(N, 2).
See also
with_nodesRebuild the path from edited nodes.
Examples
>>> from svgwriter.model.pathdata import PathData >>> PathData("M0 0 h10 Q15 5 10 10").nodes().tolist() [[0.0, 0.0], [10.0, 0.0], [15.0, 5.0], [10.0, 10.0]]
- normalized() PathData¶
Return absolute commands using only
M,L,C,Q,AandZ.HandVbecomeL, and smooth curves get their reflected control point written out.- Returns:
PathData – Normalized path data.
Examples
>>> from svgwriter.model.pathdata import PathData >>> str(PathData("M0 0 h10 v5").normalized()) 'M0 0 L10 0 L10 5'
- points() Iterator[Point]¶
Iterate points sampled along the path’s outline.
Curves and arcs are sampled at fixed resolution; lines contribute their end points.
- Yields:
Point – Successive outline points.
Examples
>>> from svgwriter.model.pathdata import PathData >>> [tuple(p) for p in PathData("M0 0 L1 1").points()] [(0.0, 0.0), (1.0, 1.0)]
- subpaths() list[PathData]¶
Split at each
moveto.Every piece is made absolute, so each can be used on its own.
- Returns:
list of PathData – One path per subpath.
Examples
>>> from svgwriter.model.pathdata import PathData >>> [str(p) for p in PathData("M0 0 h10 M20 20 h5").subpaths()] ['M0 0 H10', 'M20 20 H25']
- svg_value(precision: int = 4, *, compact: bool = False) str[source]¶
Serialize the path as text for the
dattribute.- Parameters:
- Returns:
str – The path data text.
Examples
>>> from svgwriter.model.pathdata import PathData >>> d = PathData("M0 0.5 L1.25 -0.5 L3 3") >>> d.svg_value() 'M0 0.5 L1.25 -0.5 L3 3' >>> d.svg_value(compact=True) 'M0 .5 1.25-.5 3 3'
- to_absolute() PathData¶
Return the path with every command in absolute form.
- Returns:
PathData – Equivalent path data using only uppercase commands.
Examples
>>> from svgwriter.model.pathdata import PathData >>> str(PathData("M1 1 l2 2").to_absolute()) 'M1 1 L3 3'
- transformed(transform: TransformLike) PathData¶
Bake a transform into the coordinates.
The data is normalized first, so the result uses only absolute
M,L,C,Q,AandZ; arcs stay exact arcs.- Parameters:
transform (Matrix or Transform or str) – The transform to apply; text is parsed as an SVG transform list.
- Returns:
PathData – New path data with the transform applied.
See also
normalizedThe simplification step used first.
Examples
>>> from svgwriter.model.pathdata import PathData >>> str(PathData("M0 0 h10").transformed("translate(5 5)")) 'M5 5 L15 5'
- walk() Iterator[tuple[Point, PathCommand]]¶
Iterate the commands in absolute form with the pen position before each.
- Yields:
tuple of (Point, PathCommand) – The current point before the command, and the command made absolute.
Examples
>>> from svgwriter.model.pathdata import PathData >>> [(tuple(p), str(c)) for p, c in PathData("M1 1 h2").walk()] [((0.0, 0.0), 'M1 1'), ((1.0, 1.0), 'H3')]
- with_nodes(nodes: object) PathData¶
Return the same commands with coordinates taken from an
(N, 2)array.The commands are made absolute and
H/VbecomeLso every node has both coordinates.- Parameters:
nodes (array_like) – New coordinates, in the order and shape returned by nodes.
- Returns:
PathData – Path data with the new coordinates.
- Raises:
ValueError – If the array’s shape does not match the path’s node count.
See also
nodesThe coordinate array this method consumes.
Examples
>>> from svgwriter.model.pathdata import PathData >>> d = PathData("M0 0 L10 0") >>> str(d.with_nodes(d.nodes() + 1)) 'M1 1 L11 1'