Skip to main content

Crate skia_safe

Crate skia_safe 

Source
Expand description

Safe Rust bindings for the Skia Graphics Library.

This crate provides idiomatic, memory-safe Rust wrappers around Skia’s C++ API, so that you can draw text, geometry, and images from Rust on desktop and mobile platforms, including GPU rendering backends for Vulkan, Metal, OpenGL, and Direct3D.

§Why this crate exists

Skia is a large, fast-moving C++ library that is primarily developed for use inside Chromium and Android. One of this project’s goals is to stay up to date with the current Skia milestone releases: the bindings are regenerated and the wrappers updated for every new milestone.

The current milestone is MILESTONE, and the crate version tracks it.

§Architecture

This crate is the safe layer of a two-crate stack:

  • skia-bindings builds Skia from source (or downloads a prebuilt binary) and generates the low-level extern "C" bindings with bindgen.
  • skia-safe (this crate) wraps those bindings in safe, Rust-idiomatic types.

Most Skia types are re-exported at the crate root (for example Canvas, Surface, Paint, Path, Image), so you can usually write skia_safe::Canvas without digging into the module tree.

§Getting started

[dependencies]
skia-safe = "0"

A minimal example that draws into a raster surface and saves a PNG:

use skia_safe::{Color, EncodedImageFormat, ImageInfo, Paint, Surface};

fn main() {
    let mut surface = Surface::new_raster_n32_premul((256, 256)).unwrap();
    let canvas = surface.canvas();
    canvas.clear(Color::WHITE);
    let mut paint = Paint::default();
    paint.set_anti_alias(true);
    canvas.draw_circle((128.0, 128.0), 100.0, &paint);

    let image = surface.image_snapshot();
    let png = image.encode_to_data(EncodedImageFormat::PNG).unwrap();
    std::fs::write("out.png", png.as_bytes()).unwrap();
}

§Module overview

The crate mirrors Skia’s own header layout:

  • core — the core drawing types: Surface, Paint, Path, Image, Font, Matrix, Color, and friends.
  • gpu — GPU support: the Ganesh ([gpu::ganesh]) and Graphite backends and their backend-specific APIs (D3D, GL, Metal, Vulkan).
  • effects — shaders, color filters, image filters, path effects, and runtime effects (SkSL).
  • codec — decoding of encoded images into Images and Pixmaps.
  • encode_ — encoding of images into the supported EncodedImageFormats.
  • pathops — boolean operations on Paths.
  • svg — SVG rendering.
  • skottie — Lottie (bodymovin) animation rendering.
  • [textlayout] — multi-line, styled text layout via Skia’s skparagraph module (enabled by the textlayout feature).
  • [shapers] — text shaping backends built on Skia’s SkShaper.
  • utils — miscellaneous helpers: path parsing, text drawing, shadows, cameras, and typefaces.
  • wrapper — FFI interoperability traits for the wrapper types.

§Features

By default the crate is configured for CPU (raster) rendering only. GPU backends and optional modules are enabled through Cargo features:

  • gl — OpenGL / OpenGL ES (implies Ganesh). On Linux, egl, x11, and wayland configure window-manager integration.
  • vulkan — Vulkan support (requires ganesh or graphite).
  • metal — Metal support on macOS and iOS (requires ganesh or graphite).
  • d3d — Direct3D support on Windows.
  • textlayout — text shaping with HarfBuzz and ICU, and text layout via skparagraph.
  • svg — SVG rendering.
  • skottie — Lottie animation rendering.
  • webp-encode, webp-decode, webp — WebP image format support.
  • binary-cache (default) — download prebuilt Skia binaries instead of building locally.
  • embed-icudtl (default) — embed icudtl.dat for the textlayout features.

See the package README for the full list of supported wrappers, codecs, and features.

Re-exports§

pub use codec::Codec;
pub use codec::EncodedOrigin;
pub use codec::codecs;

Modules§

annotate
Annotates a crate::Canvas with URLs, named destinations, and links to destinations, for backends that support annotations, such as PDF.
arc
Represents an arc along an oval boundary, or a closed wedge of the oval, used with crate::Canvas::draw_arc_2().
blenders
Factory functions for creating crate::Blenders, e.g. the arithmetic blender k1 * src * dst + k2 * src + k3 * dst + k4.
canvas
Canvas provides an interface for drawing, and how the drawing is clipped and transformed. Canvas contains a stack of crate::Matrix and clip values.
codec
Decoding of encoded images into crate::Images and crate::Pixmaps.
color_filter
An optional object in the drawing pipeline: when present in a crate::Paint, it is called with the source colors and returns new colors, which are then passed on to the next stage.
color_filters
Factory functions for creating crate::ColorFilters, e.g. from a color matrix, a crate::BlendMode, or a crate::ColorTable.
color_matrix
A 5x4 matrix for transforming colors, used to create color filters.
color_matrix_filter
Deprecated color filter factory functions, use crate::color_filters::lighting() instead.
colors
Named crate::Color4f constants for common colors.
contour_measure
Measures the length of a crate::Path contour and computes position and tangent matrices along it.
corner_path_effect
A crate::PathEffect that turns sharp corners into various treatments (e.g. rounded corners).
cpu
dash_path_effect
A crate::PathEffect that dashes a path by copying it with the specified intervals. Only affects stroked paths.
discrete_path_effect
A crate::PathEffect that chops a path into discrete segments and randomly displaces them.
document
High-level API for creating a document-based crate::Canvas, e.g. for PDF output; pages are created with crate::Document::begin_page().
drawable
Base-class for objects that draw into a crate::Canvas. The object has a generation ID, which is guaranteed to be unique across all drawables.
encode
Free functions to encode images into bytes, dispatching to the appropriate encoder (JPEG, PNG, WebP) based on the requested crate::EncodedImageFormat.
font
Font controls options applied when drawing and measuring text.
font_arguments
Represents a set of actual arguments for a font, including a variation position and a color palette.
font_metrics
The metrics of a font. The metric values are consistent with the Skia y-down coordinate system.
font_mgr
Provides access to the available font families and matches typefaces by family name, style, and character (fallback).
font_parameters
Parameters of a variation font: VariationAxis describes a single axis of a variable font.
font_style
Describes the style of a font: weight, width, and slant.
gpu
GPU support for Skia: the Ganesh ([crate::gpu::ganesh]) and Graphite backends, their backend-specific APIs (D3D, GL, Metal, Vulkan), and the backend-agnostic GPU types shared between them.
gradient
Gradient specifications and shader factory functions for linear, radial, and two-point conical gradients.
gradient_shaderDeprecated
Deprecated gradient shader factory functions, use the crate::gradient module instead.
graphics
Global Skia graphics state: initialization and font cache configuration.
high_contrast_config
Types used by crate::HighContrastConfig, e.g. the InvertStyle enum.
high_contrast_filter
A crate::ColorFilter that improves contrast for users with low vision, see crate::HighContrastConfig.
image
Describes a two dimensional array of pixels to draw. An Image is an immutable, thread-safe container for pixel data.
image_filter
Base class for image filters: when installed in a crate::Paint, drawing occurs as usual but as if into an offscreen, which is then filtered before being drawn to the device.
image_filters
Factory functions for creating crate::ImageFilters. For filters that take an input filter, None means the dynamic source image is used.
images
Factory functions for creating crate::Images, e.g. from a crate::Bitmap, compressed data, or a crate::Picture.
jpeg_encoder
Encoding of images into the JPEG format, with configurable quality, downsampling, and alpha handling.
line_2d_path_effect
A crate::PathEffect that maps a path onto a line and strokes it with the given width.
luma_color_filter
A crate::ColorFilter that multiplies the luma of its input into the alpha channel and sets the color channels to zero.
matrix
Holds a 3x3 matrix for transforming coordinates. This allows mapping Point and vectors with translation, scaling, skewing, rotation, and perspective.
mesh
Custom meshes: a MeshSpecification with SkSL vertex and fragment programs, and Meshes that draw vertex (and index) buffers with it.
meshes
CPU-backed mesh buffers.
named_primaries
Color primaries defined by ITU-T H.273, table 2. Names are given by the first specification referenced in the value’s row.
named_transfer_fn
Named crate::ColorSpaceTransferFn constants for common transfer functions.
overdraw_color_filter
A crate::ColorFilter that uses the value in the source alpha channel to set the destination pixel, useful for visualizing overdraw.
paint
Paint controls options applied when drawing. Paint collects all options outside of the crate::Canvas clip and crate::Canvas matrix.
path
Describes geometry as a set of contours, each beginning with a move verb and followed by lines, quadratic beziers, conics, and cubic beziers.
path_1d_path_effect
Dash a path by replicating the specified path along it.
path_2d_path_effect
A crate::PathEffect that stamps the given path at each lattice point of the transformed path.
path_builder
Helper to build a crate::Path incrementally by adding verbs, with a more convenient API than crate::Path itself.
path_effect
Base class for objects in a crate::Paint that affect the geometry of a drawing primitive before it is transformed by the canvas’ matrix and drawn.
path_measure
Measures a crate::Path: computes its length and the position and tangent at a given distance.
path_types
Types used by crate::Path: fill type, direction, segment mask, and verb.
path_utils
Utility functions for paths, e.g. computing the filled equivalent of a stroked path.
pdf
Generating PDF (Portable Document Format) output via Skia’s PDF backend (see crate::Document).
perlin_noise_shaderDeprecated
Deprecated factory functions for Perlin noise shaders, use crate::shaders::fractal_noise() and crate::shaders::turbulence() instead.
picture_recorder
Records drawing commands into a crate::Picture via a crate::Canvas.
png_encoder
Encoding of images into the PNG format, with configurable filtering and compression.
recorder
The Recorder trait and RecorderRef for recording drawing commands, implemented by e.g. crate::cpu::Recorder.
region
Describes the set of pixels used to clip crate::Canvas. Region is compact, efficiently storing a single integer rectangle, or a run length encoded array of rectangles. Region may reduce the current crate::Canvas clip, or may be drawn as one or more integer rectangles. The Region iterator returns the scan lines or rectangles contained by it, optionally intersecting a bounding rectangle.
rrect
Describes a rounded rectangle with a bounds and a pair of radii for each corner. The bounds and radii can be set so that RRect describes: a rectangle with sharp corners; a circle; an oval; or a rectangle with one or more rounded corners.
runtime_effect
Support for creating custom crate::Shaders and crate::ColorFilters from Skia’s SkSL shading language. This API is experimental and subject to change.
sampling_options
Options for sampling images: filter mode, mipmap mode, and cubic resampler.
shader
Specifies the source color(s) for what is being drawn. If a crate::Paint has no shader, the paint’s color is used.
shader_mask_filter
Deprecated factory function for creating a crate::MaskFilter from a crate::Shader. Shader mask filters will be removed in an upcoming Skia release.
shaders
Shader factory functions and Shader convenience constructors, re-exported from crate::shader::shaders.
skottie
Skottie: rendering of Lottie (bodymovin) animations via Skia’s Skottie module (see [Animation]).
stroke_rec
Describes how a crate::Path is stroked: style, width, miter, cap, and join.
surface
Describes a drawing destination: a Surface manages the pixels or GPU resources that a crate::Canvas draws into.
surfaces
Factory functions for creating crate::Surfaces, e.g. raster, null, and GPU-backed surfaces.
svg
SVG (Scalable Vector Graphics) support: an SVG Canvas and the SVG DOM types for rendering SVG documents.
table_color_filter
Deprecated color filter factory functions that apply a lookup table to colors, use crate::color_filters::table() and crate::color_filters::table_argb() instead.
table_mask_filter
Deprecated crate::MaskFilter factory functions that apply a table lookup to the alpha values of a mask. Will be removed in an upcoming Skia release.
tiled_image_utils
SkTiledImageUtils’ self::draw_image()/self::draw_image_rect() methods are intended to be direct replacements for their Canvas equivalents. The SkTiledImageUtils calls will break crate::Bitmap-backed Images into smaller tiles and draw them if the original image is too large to be uploaded to the GPU. If the original image doesn’t need tiling or is already gpu-backed the self::draw_image()/self::draw_image_rect() calls will fall through to the matching Canvas call.
trim_path_effect
A crate::PathEffect that returns a subset of a path, given start and stop t values between 0 and 1.
typeface
Describes the typeface and style of a font; a Typeface is used by crate::Font to draw text.
utils
Miscellaneous utility helpers for working with Skia: path parsing, text drawing, shadows, cameras, and typefaces.
vertices
An immutable set of vertex data that can be used with crate::Canvas::draw_vertices().
wrapper
FFI interoperability for skia-safe’s wrapper types.
yuva_info
Specifies the structure of planes for a YUV image with optional alpha. The actual planar data is not part of this structure and depending on usage is in external textures or pixmaps.
yuva_pixmap_info
Data types and supported data types for the planes of a crate::YUVAPixmapInfo.
yuva_pixmaps
Describes and stores the crate::Pixmap planes of a YUVA image: YUVAPixmapInfo specifies the plane layout, YUVAPixmaps stores the pixel data.

Macros§

native_transmutable
Macro to mark a Rust type as NativeTransmutable and test its layout.
require_base_type
require_type_equality
unsafe_send_sync
Macro that implements Send and Sync.
variant_name
Macro that verifies a variant name at compile time.

Structs§

Arc
Represents an arc along an oval boundary, or a closed wedge of the oval.
Borrows
Canvas
Canvas provides an interface for drawing, and how the drawing is clipped and transformed. Canvas contains a stack of Matrix and clip values.
Color
32-bit ARGB color value, unpremultiplied. Color components are always in a known order. This is different from SkPMColor, which has its bytes in a configuration dependent order, to match the format of BGRA 8888 color type bitmaps. Color is the type used to specify colors in crate::Paint and in gradients.
Color4f
ColorChannelFlag
ColorSpacePrimaries
ColorSpaceTransferFn
CubicMap
Fast evaluation of a cubic ease-in / ease-out curve. This is defined as a parametric cubic curve inside the unit square.
CubicResampler
Specify b and c (each between 0…1) to create a shader that applies the corresponding cubic reconstruction filter to the image.
DateTime
Document
FilterOptionsDeprecated
FontArguments
Represents a set of actual arguments for a font.
FontMetrics
FontStyle
FourByteTag
HSV
Handle
Wraps a native type that can be represented in Rust memory.
HighContrastConfig
Configuration struct for ColorFilter::high_contrast().
IPoint
IRect
ISize
IVector
Iter
M44
4x4 matrix used by crate::Canvas and other parts of Skia.
Matrix
OwnedCanvas
Represents a Canvas that is owned and dropped when it goes out of scope and is bound to the lifetime of some other value (an array of pixels for example).
PathContourIter
PathContourIterRec
PathIter
PathIterRec
PathSegmentMask
Pixmap
Point
Point3
RCHandle
A wrapper type represented by a reference counted pointer to the native type.
RGB
RRect
RSXform
A compressed form of a rotation+scale matrix.
RecorderRef
Rect
RefHandle
A wrapper type that represents a native type with a pointer to the native object.
SamplingOptions
Sendable
Size
SurfaceProps
Describes properties and constraints of a given surface. The rendering engine can parse these during drawing, and can sometimes optimize its performance (e.g. disabling an expensive feature).
SurfacePropsFlags
TextBlobRun
V2
V3
V4
XYZD50Hash

Enums§

AlphaType
Describes how to interpret the alpha component of a pixel. A pixel may be opaque, or alpha, describing multiple levels of transparency.
AutoCanvasRestore
BlendMode
Blends are operators that take in two colors (source, destination) and return a new color. Many of these operate the same on all 4 components: red, green, blue, alpha. For these, we just document what happens to one component, rather than naming each one separately.
BlendModeCoeff
BlurStyle
ClipOp
CodecResult
Error codes for various Codec methods.
ColorChannel
ColorType
Describes how pixel bits encode color. A pixel may be an alpha mask, a grayscale, RGB, or ARGB.
CoverageMode
Describes geometric operations (ala crate::region::RegionOp) that can be applied to coverage bytes. These can be thought of as variants of porter-duff (crate::BlendMode) modes, but only applied to the alpha channel.
EncodedImageFormat
Enum describing format of encoded data.
FilterMode
MipmapMode
PaintCap
Cap draws at the beginning and end of an open path contour.
PaintJoin
Join specifies how corners are drawn when a shape is stroked. Join affects the four corners of a stroked rectangle, and the connected segments in a stroked path.
PaintStyle
Set the Style to fill, stroke, or both fill and stroke geometry. The stroke and fill share all paint attributes; for instance, they are drawn with the same color.
PixelGeometry
Description of how the LCD strips are arranged for each pixel. If this is unknown, or the pixels are meant to be “portable” and/or transformed before showing (e.g. rotated, scaled) then use PixelGeometry::Unknown.
TextEncoding
TextureCompressionType
Skia | GL_COMPRESSED_* | MTLPixelFormat* | VK_FORMAT_*_BLOCK
TileMode
Describes how a shader draws outside of its original bounds: TileMode::Clamp replicates the edge color, TileMode::Repeat repeats the image horizontally and vertically, TileMode::Mirror repeats the image with alternating mirror images so adjacent images always seam, and TileMode::Decal draws only within the original domain, returning transparent-black everywhere else.
YUVColorSpace

Constants§

EMPTY_IRECT
MILESTONE

Traits§

ConditionallySend
Contains
EncodedText
Trait representing encoded text.
Flattenable
NativeFlattenable
Pixel
Implement this trait to use a pixel type in Handle<Pixmap>::pixels().
QuickReject
Recorder
RoundOut
Scalar
Scalars

Functions§

as_utf16_unchecked⚠
Treat a &[u16] as UTF16 encoded text.
as_utf32_unchecked⚠
Treat a &[u32] as UTF32 encoded text.
as_winding
Returns a path with fill type winding to area equivalent to the input. Does not detect if path contains contours which contain self-crossings or cross other contours; in these cases, may return a result even though it does not fill same area as the input.
op
Set the resulting path to the result of applying the operator to one and two: this = (one op two). The resulting path will be constructed from non-overlapping contours. The curve order is reduced where possible so that cubics may be turned into quadratics, and quadratics maybe turned into lines.
pre_multiply_argb
Returns a PMColor value from unpremultiplied 8-bit component values.
pre_multiply_color
Returns the premultiplied color closest to c. Multiplies the c RGB components by the c alpha, and arranges the bytes to match the format of crate::ColorType::N32.
radians_to_degrees
simplify
Return a path with a set of non-overlapping contours that describe the same area as the original path. The curve order is reduced where possible so that cubics may be turned into quadratics, and quadratics maybe turned into lines.
swap_rb
Swizzles the byte order of 32-bit pixels, swapping R and B (RGBA ↔ BGRA).
swap_rb_inplace
Swaps R and B in place (RGBA ↔ BGRA).
tight_boundsDeprecated
Set the resulting rectangle to the tight bounds of the path.

Type Aliases§

BBHFactory
BBoxHierarchy
Bitmap
Bitmap describes a two-dimensional raster pixel array. Bitmap is built on ImageInfo, containing integer width and height, ColorType and AlphaType describing the pixel format, and ColorSpace describing the range of colors. Bitmap points to PixelRef, which describes the physical array of pixels. ImageInfo bounds may be located anywhere fully inside PixelRef bounds.
Blender
Blender represents a custom blend function in the Skia pipeline. A blender combines a source color (the result of our paint) and destination color (from the canvas) into a final color.
Color3f
ColorFilter
ColorInfo
Describes pixel and encoding. ImageInfo can be created from ColorInfo by providing dimensions.
ColorMatrix
ColorSpace
ColorTable
ColorTable holds the lookup tables for each channel (ARGB) used to define the filter behavior of SkColorFilters::Table, and provides a way to share the table data between client code and the returned crate::ColorFilter. Once created, an ColorTable is immutable.
Context
Skia’s central context object for shared resources and internal caches.
ContextOptions
Options shared by Skia’s raster and GPU context factories.
ContourMeasure
ContourMeasureIter
Data
DataTable
Like crate::Data, DataTable holds an immutable data buffer. The data buffer is organized into a table of entries, each with a length, so the entries are not required to all be the same size.
Drawable
Base-class for objects that draw into Canvas.
Font
Font controls options applied when drawing and measuring text.
FontHinting
FontMgr
FontStyleSet
GlyphId
Image
Image describes a two dimensional array of pixels to draw. The pixels may be decoded in a raster bitmap, encoded in a Picture or compressed data stream, or located in GPU memory as a GPU texture.
ImageFilter
ImageGenerator
ImageInfo
Describes pixel dimensions and encoding. crate::Bitmap, crate::Image, crate::Pixmap, and crate::Surface can be created from ImageInfo. ImageInfo can be retrieved from crate::Bitmap and crate::Pixmap, but not from crate::Image and crate::Surface. For example, crate::Image and crate::Surface implementations may defer pixel depth, so may not completely specify ImageInfo.
MaskFilter
MaskFilter is the base class for object that perform transformations on the mask before drawing it. An example subclass is Blur.
Mesh
A vertex buffer, a topology, optionally an index buffer, and a compatible MeshSpecification.
MeshSpecification
A specification for custom meshes. Specifies the vertex buffer attributes and stride, the vertex program that produces a user-defined set of varyings, and a fragment program that ingests the interpolated varyings and produces local coordinates for shading and optionally a color.
OpBuilder
Perform a series of path operations, optimized for unioning many paths together.
PMColor
Paint
Paint controls options applied when drawing.
Path
Path contain geometry. Path may be empty, or contain one or more verbs that outline a figure. Path always starts with a move verb to a Cartesian coordinate, and may be followed by additional verbs that add lines or curves. Adding a close verb makes the geometry into a continuous loop, a closed contour. Path may contain any number of contours, each beginning with a move verb.
PathBuilder
PathDirection
PathEffect
PathFillType
PathMeasure
PathOp
The logical operations that can be performed when combining two paths.
PathVerb
Picture
PictureRecorder
PixelRef
Region
RuntimeEffect
RuntimeEffect supports creating custom Shader and ColorFilter objects using Skia’s SkSL shading language.
SamplingModeDeprecated
Shader
StrikeRef
StrikeRef is a lightweight, thread-safe handle to a resolved font strike.
StrokeRec
Surface
Surface is responsible for managing the pixels that a canvas draws into. The pixels can be allocated either in CPU memory (a raster surface) or on the GPU (a RenderTarget surface). Surface takes care of allocating a Canvas that will draw into the surface. Call Surface::canvas() to use that canvas (but don’t delete it, it is owned by the surface). Surface always has non-zero dimensions. If there is a request for a new surface, and either of the requested dimensions are zero, then None will be returned.
TextBlob
TextBlobBuilder
Helper class for constructing TextBlob.
TextBlobIter
Typeface
Unichar
Vector
Vector3
Vertices
An immutable set of vertex data that can be used with crate::Canvas::draw_vertices.
YUVAInfo
Specifies the structure of planes for a YUV image with optional alpha. The actual planar data is not part of this structure and depending on usage is in external textures or pixmaps.
YUVAPixmapInfo
YUVAInfo combined with per-plane ColorTypes and row bytes. Fully specifies the Pixmap`s for a YUVA image without the actual pixel memory and data.
YUVAPixmaps
Helper to store Pixmap planes as described by a YUVAPixmapInfo. Can be responsible for allocating/freeing memory for pixmaps or use external memory.
scalar