Colors¶
Colors and paints.
Color parsing and the <paint> type.
- as_color(value: Color | str | Sequence[float]) Color[source]¶
Coerce a
ColorLikeinto aColor.- Parameters:
value (Color or str or sequence of float) – A color, color text, or a 3- or 4-sequence of floats in
0..1.- Returns:
Color – value itself if it is already a Color.
- Raises:
ValueError – For unknown names or channels outside
0..1.TypeError – For anything that is not a color.
See also
parse_colorParse text only.
Examples
>>> from svgwriter.model.color import as_color >>> as_color("blue").hex '#0000ff' >>> as_color((1, 0, 0)).hex '#ff0000'
- class PaintKeyword(*values)[source]¶
Bases:
KeywordThe paint keywords that are not colors.
Members compare equal to their SVG text.
Examples
>>> from svgwriter.model.color import PaintKeyword >>> PaintKeyword.CURRENT_COLOR.value 'currentColor' >>> PaintKeyword("none") is PaintKeyword.NONE True >>> str(PaintKeyword.CURRENT_COLOR) 'currentColor'
- NONE = 'none'¶
- CURRENT_COLOR = 'currentColor'¶
- INHERIT = 'inherit'¶
- class PaintRef(iri: FuncIRI, fallback: Color | PaintKeyword | None = None)[source]¶
Bases:
objectA paint server reference with an optional fallback.
- Parameters:
iri (FuncIRI) – The
url(#id)reference to a gradient or pattern.fallback (Color or PaintKeyword, optional) – Paint used when the reference cannot be resolved. Defaults to None.
See also
parse_paintParse
fillorstroketext.
Examples
>>> from svgwriter.model.color import PaintRef, parse_color >>> from svgwriter.model.attributes.reference import FuncIRI >>> str(PaintRef(FuncIRI("#grad"), parse_color("red"))) 'url(#grad) red'
- fallback: Color | PaintKeyword | None = None¶
- svg_value(precision: int = 4) str[source]¶
Serialize the reference and its fallback.
- Parameters:
precision (int, optional) – Maximum number of decimal places. Defaults to the library default precision.
- Returns:
str –
url(...)optionally followed by the fallback.
Examples
>>> from svgwriter.model.color import parse_paint >>> parse_paint("url(#grad) none").svg_value() 'url(#grad) none'
- clamp(value: N, low: N, high: N) N[source]¶
Clamp a value into a range.
- Parameters:
- Returns:
int or float – low if value is below it, high if above, otherwise value.
Examples
>>> from svgwriter.model.color import clamp >>> clamp(5, 0, 1) 1 >>> clamp(-0.5, 0.0, 1.0) 0.0
- parse_color(text: str) Color[source]¶
Parse a color keyword, hex or CSS Color 4 function into sRGB.
Functions:
rgb()/rgba()(numbers are 0..255, percentages 0..100%),hsl()/hsla(),hwb(),hsv()/hsva(),lab(),lch(),oklab(),oklch(),color(<space> r g b)withsrgb,srgb-linear,display-p3,a98-rgb,rec2020,xyz/xyz-d65orxyz-d50, anddevice-cmyk(). Both the comma syntax and the modern space-separated syntax with/ alphawork;nonestands for a zero channel; hues takedeg,rad,gradorturn. Colors outside the sRGB gamut are clipped to it.device-cmyk()is the naive formula with no profile; real CMYK goes through a trailingicc-color(...), which is preserved. Results are cached.- Parameters:
text (str) – Color text such as
"tomato","#f80","rgb(255 0 0 / 50%)"or"oklch(62.8% 0.2577 29.23)".- Returns:
Color – The parsed color.
- Raises:
ValueError – If the text is not a recognized color.
See also
as_colorAlso accepts colors and channel sequences.
Examples
>>> from svgwriter.model.color import parse_color >>> parse_color("tomato").uint8 (255, 99, 71, 255) >>> parse_color("hsl(120, 100%, 50%)").hex '#00ff00'
- parse_paint(text: str) Color | PaintKeyword | PaintRef[source]¶
Parse a
fillorstrokevalue.- Parameters:
text (str) – A keyword (
none,currentColor,inherit), a color, or aurl(#id)reference optionally followed by a fallback.- Returns:
Color or PaintKeyword or PaintRef – The parsed paint.
- Raises:
ValueError – If the text is not a valid paint, or a fallback is itself a reference.
See also
parse_colorParse colors only.
Examples
>>> from svgwriter.model.color import parse_paint >>> parse_paint("none") <PaintKeyword.NONE: 'none'> >>> str(parse_paint("url(#grad) red")) 'url(#grad) red'
- class Color(r: float, g: float, b: float, a: float = 1.0, icc: str | None = None, name: str | None = None, *, source: tuple[str, tuple[float, float, float]] | None = None)[source]¶
Bases:
ColorText,ColorBlending,ColorAdjustments,ColorTones,ColorDifference,DrawableAn sRGB color with straight alpha; every channel is a float in
0..1.Colors are immutable, support
+(even mix),*and/(scaling), and iterate asr, g, b, a.- Parameters:
r (float) – Red, green and blue in
0..1.g (float) – Red, green and blue in
0..1.b (float) – Red, green and blue in
0..1.a (float, optional) – Alpha (opacity) in
0..1; 1 is opaque. Defaults to 1.0.icc (str, optional) – An
icc-color(...)specification kept alongside the sRGB value. Defaults to None.name (str, optional) – Keyword written instead of hex (set when parsed from a name); ignored when comparing. Defaults to None.
source (tuple of (str, tuple of float), optional) – The colour space and unclipped channels the color was given in, as set by
from_space(), CSS Color 4 text and mixing; None for plain sRGB. Defaults to None.
- Raises:
ValueError – If any channel is outside
0..1.
See also
as_colorCoerce names, tuples and colors into a Color.
parse_colorParse CSS color text.
Notes
Everything that takes a color also takes a
ColorLike: a name or CSS string, aColor, or a 3/4-tuple of floats in0..1(as in matplotlib). Usefrom_uint8()for0..255values.r,gandbare always sRGB, clipped to its gamut, and drivehex,rgbaand SVG output. A color given in another space (oklch(...),color(display-p3 ...)) also keeps that space and its exact values insource:coords(),mix(),tint(),delta()andto_css()work from them, so wide-gamut colors are not clipped before they are mixed. SVG 1.1 has no alpha in colors, so a translucentfill/stroke/stop-color/flood-coloralso writes the matching*-opacityattribute.Examples
>>> from svgwriter.model.color import Color >>> Color(1, 0.5, 0).hex '#ff8000' >>> Color.parse("#f80").uint8 (255, 136, 0, 255) >>> Color.from_uint8(255, 0, 0, 128).a 0.5019607843137255 >>> str(Color.parse("red") + "blue") '#800080' >>> Color.parse("rgba(0, 0, 255, 0.25)").a 0.25
- classmethod parse(text: str) Color[source]¶
Parse a name, hex or CSS Color 4 function (see
parse_color()).- Parameters:
text (str) – Color text.
- Returns:
Color – The parsed color.
- Raises:
ValueError – If the text is not a recognized color.
See also
parse_colorThe equivalent function.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("#f80").hex '#ff8800'
- classmethod from_uint8(r: int, g: int, b: int, a: int = 255) Color[source]¶
Build a color from
0..255channels.- Parameters:
- Returns:
Color – The color with channels scaled to
0..1.
Examples
>>> from svgwriter.model.color import Color >>> Color.from_uint8(255, 0, 0).hex '#ff0000'
- classmethod from_space(space: str, coords: Sequence[float], alpha: float = 1.0) Color[source]¶
Build a color from channels in any colour space, keeping them exactly.
- Parameters:
- Returns:
Color – The color:
r,gandbhold its sRGB value clipped to the gamut andsourcekeeps space and coords (None for an in-gamut sRGB color).- Raises:
ValueError – If space is unknown or alpha is outside
0..1.
See also
coordsRead the channels back in any space.
Examples
>>> from svgwriter.model.color import Color >>> p3 = Color.from_space("display-p3", (0, 1, 0)) >>> p3.hex, p3.space, p3.in_gamut ('#00ff00', 'display-p3', False) >>> Color.from_space("oklch", (0.628, 0.2577, 29.23)).hex '#ff0000'
- classmethod from_hsl(hue: float, saturation: float, lightness: float, alpha: float = 1.0) Color[source]¶
Build a color from hue, saturation and lightness.
- Parameters:
- Returns:
Color – The corresponding sRGB color.
Examples
>>> from svgwriter.model.color import Color >>> Color.from_hsl(240, 1, 0.5).hex '#0000ff'
- complement() Color¶
The color with its hue turned half way round.
- Returns:
Color – The complementary color.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("blue").complement().hex '#ffff00'
- contrast(other: ColorLike) float¶
The WCAG 2 contrast ratio with another color, from 1 to 21.
- Parameters:
other (Color or str or sequence of float) – The second color; the order does not matter. Alpha is ignored.
- Returns:
float –
(L1 + 0.05) / (L2 + 0.05)withL1the lighter relative luminance. Body text needs 4.5 for WCAG AA, large text 3.
Examples
>>> from svgwriter.model.color import Color >>> round(Color.parse("black").contrast("white"), 1) 21.0
- coords(space: str | None = None) tuple[float, float, float]¶
The three channels in a colour space, unclipped.
- Parameters:
space (str, optional) –
"srgb","srgb-linear","display-p3","a98-rgb","rec2020","xyz-d65","xyz-d50","lab","lch","oklab"or"oklch". Defaults to None, the color’s ownspace.- Returns:
tuple of float – The channels, converted from the values the color was given in, so colors outside the sRGB gamut keep their real values. Lab and LCH use a D50 white with L in
0..100; hues are in degrees.- Raises:
ValueError – If space is unknown.
Examples
>>> from svgwriter.model.color import Color >>> [round(c, 4) for c in Color.parse("red").coords("display-p3")] [0.9175, 0.2003, 0.1386] >>> Color.parse("color(display-p3 1 0 0)").coords() (1.0, 0.0, 0.0) >>> [round(c, 3) for c in Color.parse("color(display-p3 1 0 0)").coords("srgb")] [1.093, -0.227, -0.15]
- darken(amount: Opacity) Color¶
Lower HSL lightness by an amount.
- Parameters:
amount (float) – Decrease in lightness on a
0..1scale.- Returns:
Color – The adjusted color.
See also
lightenRaise lightness instead.
Examples
>>> from svgwriter.model.color import Color >>> Color(0.5, 0.5, 0.5).darken(0.2).hex '#4c4c4c'
- delta(other: ColorLike) float¶
The distance to another color in OKLab (ΔE OK).
- Parameters:
other (Color or str or sequence of float) – The second color. Alpha is ignored.
- Returns:
float – The Euclidean distance between the exact OKLab values: 0 for the same color, about 0.02 for a just noticeable difference, 1 from black to white.
See also
delta_e2000The CIEDE2000 difference used in print and colour science.
Examples
>>> from svgwriter.model.color import Color >>> round(Color.parse("black").delta("white"), 4) 1.0 >>> Color.parse("red").delta("#ff0000") 0.0
- delta_e2000(other: ColorLike) float¶
The CIEDE2000 difference to another color (ΔE00), from their CIE Lab values.
- Parameters:
other (Color or str or sequence of float) – The second color. Alpha is ignored.
- Returns:
float – ΔE00: below 1 is hard to see, 2 to 10 is visible at a glance, and very different colors reach 100 and more.
See also
deltaThe simpler OKLab distance.
ciede2000The formula on raw Lab values.
Notes
Lab here is CSS Color 4’s (D50 white), so
lab(...)colors are compared exactly.Examples
>>> from svgwriter.model.color import Color >>> round(Color.parse("lab(50 2.6772 -79.7751)").delta_e2000("lab(50 0 -82.7485)"), 4) 2.0425
- desaturate(amount: Opacity) Color¶
Lower HSL saturation by an amount.
- Parameters:
amount (float) – Decrease in saturation on a
0..1scale.- Returns:
Color – The adjusted color.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("red").desaturate(1).hex '#808080'
- gamma(exponent: float) Color¶
Raise every sRGB channel to a power, as an SVG
feFuncX type="gamma"does.- Parameters:
exponent (float) – The power, above 0: above 1 darkens the mid-tones, below 1 lightens them; black and white stay put.
- Returns:
Color – The adjusted color; alpha is unchanged.
- Raises:
ValueError – If exponent is not above 0.
Examples
>>> from svgwriter.model.color import Color >>> Color(0.5, 0.5, 0.5).gamma(2).hex '#404040' >>> Color(0.25, 0.25, 0.25).gamma(0.5).hex '#808080'
- grayscale() Color¶
The grey of the same perceived lightness (OKLab lightness of the exact color, no chroma).
- Returns:
Color – A neutral grey with the same alpha.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("yellow").grayscale().hex '#f4f4f4'
- property hex: str¶
#rrggbb, or#rrggbbaawhen translucent.Examples
>>> from svgwriter.model.color import Color >>> Color(1, 0.5, 0).hex '#ff8000' >>> Color(1, 0, 0, 0.5).hex '#ff000080'
- Type:
The hex form
- property hsl: tuple[float, float, float]¶
Hue in degrees, saturation and lightness in
0..1.Examples
>>> from svgwriter.model.color import Color >>> Color.parse("blue").hsl (240.0, 1.0, 0.5)
- hue_shift(degrees: float) Color¶
Turn the HSL hue.
- Parameters:
degrees (float) – Angle to add to the hue; any value, taken modulo 360.
- Returns:
Color – The color with the same saturation, lightness and alpha.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("red").hue_shift(120).hex '#00ff00'
- property in_gamut: bool¶
Whether the color fits the sRGB gamut, so its sRGB output is exact rather than clipped.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("teal").in_gamut, Color.parse("color(display-p3 0 1 0)").in_gamut (True, False)
- invert() Color¶
The negative: every channel
cbecomes1 - c; alpha is kept.- Returns:
Color – The inverted color.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("#ff8000").invert().hex '#007fff'
- property is_dark: bool¶
Whether white text reads better on this color than black text.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("navy").is_dark, Color.parse("yellow").is_dark (True, False)
- property is_light: bool¶
Whether black text reads better on this color than white text; the opposite of
is_dark.Examples
>>> from svgwriter.model.color import Color >>> Color.parse("white").is_light True
- lighten(amount: Opacity) Color¶
Raise HSL lightness by an amount.
- Parameters:
amount (float) – Change in lightness on a
0..1scale; negative darkens. The result is clamped.- Returns:
Color – The adjusted color.
See also
darkenLower lightness instead.
Examples
>>> from svgwriter.model.color import Color >>> Color(0.5, 0.5, 0.5).lighten(0.2).hex '#b2b2b2'
- property luminance: float¶
Relative luminance per WCAG, from 0 (black) to 1 (white).
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("black").luminance 0.0 >>> round(Color.parse("white").luminance, 6) 1.0
- mix(other: ColorLike, weight: Opacity = 0.5, space: MixSpace = 'srgb') Color¶
Blend with another color in a chosen space.
- Parameters:
other (Color or str or sequence of float) – The color to mix in.
weight (float, optional) – Share of other in the result, from 0 to 1. Defaults to 0.5.
space ({"srgb", "linear", "display-p3", "lab", "lch", "oklab", "oklch", "xyz"}, optional) – Where to interpolate: sRGB channels, linear-light sRGB (physically even blending of light), Display P3, CIE Lab or LCH, OKLab (perceptually even steps), OKLCH (OKLab with hue taken the shorter way round, so saturated colors stay saturated) or CIE XYZ (D65). Defaults to
"srgb".
- Returns:
Color – The blended color; alpha is blended linearly. When either color carries a
source(a wide-gamut or non-sRGB color), both are mixed from their exact values and the result keeps the mixed values in space, so nothing is clipped until output.- Raises:
ValueError – If other is not a valid color or space is unknown.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("red").mix("blue", 0.25).hex '#bf0040' >>> Color.parse("red").mix("blue", 0.5, space="oklch").hex '#ba00c2' >>> p3 = Color.parse("color(display-p3 0 1 0)").mix("white", 0.5, space="display-p3") >>> p3.to_css("display-p3") 'color(display-p3 0.5 1 0.5)'
- property opaque: Color¶
This color with alpha 1.
Examples
>>> from svgwriter.model.color import Color >>> Color(1, 0, 0, 0.5).opaque.a 1.0
- posterize(steps: int) Color¶
Round every sRGB channel to one of steps evenly spaced levels.
- Parameters:
steps (int) – Levels per channel, at least 2; 2 leaves only 0 and 1.
- Returns:
Color – The quantized color; alpha is unchanged.
- Raises:
ValueError – If steps is below 2.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("#5a9ad0").posterize(2).hex '#00ffff' >>> Color.parse("#5a9ad0").posterize(5).hex '#4080bf'
- readable(first: ColorLike = 'black', second: ColorLike = 'white') Color¶
Of two colors, the one with more contrast on this color, for text on it.
- Parameters:
- Returns:
Color – first or second, whichever has the higher
contrast(); first on a tie.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("#0f766e").readable().hex '#ffffff' >>> Color.parse("#fbbf24").readable("#1f2933", "#ffffff").hex '#1f2933'
- property rgb: tuple[float, float, float]¶
The red, green and blue channels as floats in
0..1.Examples
>>> from svgwriter.model.color import Color >>> Color(1, 0.5, 0).rgb (1, 0.5, 0)
- property rgba: tuple[float, float, float, float]¶
The red, green, blue and alpha channels as floats in
0..1.Examples
>>> from svgwriter.model.color import Color >>> Color(1, 0.5, 0).rgba (1, 0.5, 0, 1.0)
- saturate(amount: Opacity) Color¶
Raise HSL saturation by an amount.
- Parameters:
amount (float) – Change in saturation on a
0..1scale; negative desaturates. The result is clamped.- Returns:
Color – The adjusted color, with the same hue, lightness and alpha.
See also
desaturateLower saturation instead.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("#806060").saturate(0.5).hex '#b82828'
- scale(factor: float) Color¶
Multiply the color channels by a factor.
Alpha is unchanged and channels are clamped to
0..1.- Parameters:
factor (float) – Multiplier; above 1 brightens, below 1 darkens.
- Returns:
Color – The scaled color.
Examples
>>> from svgwriter.model.color import Color >>> Color(0.5, 0.2, 0.1).scale(2).hex '#ff6633'
- sepia(amount: Opacity = 1.0) Color¶
Tone the color brown like an old photograph, as the CSS
sepia()filter does.- Parameters:
amount (float, optional) – Strength from 0 (unchanged) to 1 (full sepia). Defaults to 1.0.
- Returns:
Color – The toned sRGB color, clipped to the gamut; alpha is unchanged.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("#3366cc").sepia().hex '#897a5f' >>> Color.parse("#3366cc").sepia(0).hex '#3366cc'
- shade(amount: Opacity) Color¶
Mix with black in OKLab.
- Parameters:
amount (float) – Share of black, from 0 (unchanged) to 1 (black).
- Returns:
Color – The darker color, with the same alpha.
See also
tintMix with white instead; its notes explain the choice of OKLab.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("#0f766e").shade(0.5).hex '#022926'
- property space: str¶
"srgb", or the space kept from CSS text or a mix.Examples
>>> from svgwriter.model.color import Color >>> Color.parse("red").space, Color.parse("oklch(0.7 0.3 145)").space ('srgb', 'oklch')
- Type:
The colour space the color was given in
- svg_value(precision: int = 4) str¶
Return SVG 1.1 color text.
The name or
#rrggbbis written; alpha is not part of the text and is emitted separately as an opacity attribute.- Parameters:
precision (int, optional) – Unused; accepted for a uniform interface. Defaults to the library default precision.
- Returns:
str – The color text, followed by any ICC specification.
Examples
>>> from svgwriter.model.color import Color >>> Color(1, 0, 0, 0.5).svg_value() '#ff0000'
- tint(amount: Opacity) Color¶
Mix with white in OKLab.
- Parameters:
amount (float) – Share of white, from 0 (unchanged) to 1 (white).
- Returns:
Color – The lighter color, with the same alpha.
Notes
White and black sit on OKLab’s neutral axis, so the straight line to either keeps the OKLab hue exactly while lightness changes in perceptually even steps; mixing in sRGB drifts the hue (blue turns purple on the way to white).
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("#0f766e").tint(0.5).hex '#91b9b4' >>> Color.parse("blue").tint(0).hex '#0000ff'
- to_css(space: Literal['srgb', 'hsl', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'srgb-linear', 'display-p3', 'a98-rgb', 'rec2020', 'xyz-d65', 'xyz-d50'] = 'srgb', precision: int = 4) str¶
Return CSS text for the color in a chosen space.
- Parameters:
space (str, optional) –
"srgb"writes the name or hex when opaque andrgba(...)otherwise, clipped to the sRGB gamut."hsl"and"hwb"write those sRGB functions."lab","lch","oklab"and"oklch"write their own functions and"srgb-linear","display-p3","a98-rgb","rec2020","xyz-d65"and"xyz-d50"writecolor(<space> ...); these keep colours outside the sRGB gamut. Defaults to"srgb".precision (int, optional) – Decimals of each channel. Defaults to the library default precision.
- Returns:
str – The CSS color; a translucent color ends with
/ alphain every space but"srgb".- Raises:
ValueError – If space is unknown.
See also
coordsThe channels themselves.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("red").to_css() 'red' >>> Color(1, 0, 0, 0.5).to_css() 'rgba(255, 0, 0, 0.5)' >>> Color.parse("red").to_css("oklch", precision=2) 'oklch(0.63 0.26 29.23)' >>> Color.parse("color(display-p3 1 0 0)").to_css("display-p3") 'color(display-p3 1 0 0)' >>> Color.parse("blue").with_alpha(0.5).to_css("hsl") 'hsl(240 100% 50% / 0.5)'
- property uint8: tuple[int, int, int, int]¶
RGBA as
0..255integers.Examples
>>> from svgwriter.model.color import Color >>> Color(1, 0.5, 0).uint8 (255, 128, 0, 255)
- with_alpha(alpha: Opacity) Color¶
Return the same color with a different alpha.
- Parameters:
alpha (float) – New opacity in
0..1.- Returns:
Color – A copy with the given alpha.
- Raises:
ValueError – If alpha is outside
0..1.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("red").with_alpha(0.5).a 0.5
- with_icc(spec: str) Color¶
Return the color with an ICC specification attached.
- Parameters:
spec (str) – An
icc-color(...)specification, written after the sRGB fallback.- Returns:
Color – A copy carrying the specification.
Examples
>>> from svgwriter.model.color import Color >>> Color.parse("red").with_icc("icc-color(profile, 1)").svg_value() 'red icc-color(profile, 1)'