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-bindingsbuilds Skia from source (or downloads a prebuilt binary) and generates the low-levelextern "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 intoImages andPixmaps.encode_— encoding of images into the supportedEncodedImageFormats.pathops— boolean operations onPaths.svg— SVG rendering.skottie— Lottie (bodymovin) animation rendering.- [
textlayout] — multi-line, styled text layout via Skia’sskparagraphmodule (enabled by thetextlayoutfeature). - [
shapers] — text shaping backends built on Skia’sSkShaper. 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, andwaylandconfigure window-manager integration.vulkan— Vulkan support (requiresganeshorgraphite).metal— Metal support on macOS and iOS (requiresganeshorgraphite).d3d— Direct3D support on Windows.textlayout— text shaping with HarfBuzz and ICU, and text layout viaskparagraph.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) — embedicudtl.datfor thetextlayoutfeatures.
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::Canvaswith 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 blenderk1 * src * dst + k2 * src + k3 * dst + k4. - canvas
Canvasprovides an interface for drawing, and how the drawing is clipped and transformed.Canvascontains a stack ofcrate::Matrixand clip values.- codec
- Decoding of encoded images into
crate::Images andcrate::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, acrate::BlendMode, or acrate::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::Color4fconstants for common colors. - contour_
measure - Measures the length of a
crate::Pathcontour and computes position and tangent matrices along it. - corner_
path_ effect - A
crate::PathEffectthat turns sharp corners into various treatments (e.g. rounded corners). - cpu
- dash_
path_ effect - A
crate::PathEffectthat dashes a path by copying it with the specified intervals. Only affects stroked paths. - discrete_
path_ effect - A
crate::PathEffectthat 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 withcrate::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
Fontcontrols 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:
VariationAxisdescribes 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_
shader Deprecated - Deprecated gradient shader factory functions, use the
crate::gradientmodule instead. - graphics
- Global Skia graphics state: initialization and font cache configuration.
- high_
contrast_ config - Types used by
crate::HighContrastConfig, e.g. theInvertStyleenum. - high_
contrast_ filter - A
crate::ColorFilterthat improves contrast for users with low vision, seecrate::HighContrastConfig. - image
- Describes a two dimensional array of pixels to draw. An
Imageis 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,Nonemeans the dynamic source image is used. - images
- Factory functions for creating
crate::Images, e.g. from acrate::Bitmap, compressed data, or acrate::Picture. - jpeg_
encoder - Encoding of images into the JPEG format, with configurable quality, downsampling, and alpha handling.
- line_
2d_ path_ effect - A
crate::PathEffectthat maps a path onto a line and strokes it with the given width. - luma_
color_ filter - A
crate::ColorFilterthat 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
Pointand vectors with translation, scaling, skewing, rotation, and perspective. - mesh
- Custom meshes: a
MeshSpecificationwith SkSL vertex and fragment programs, andMeshes 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::ColorSpaceTransferFnconstants for common transfer functions. - overdraw_
color_ filter - A
crate::ColorFilterthat uses the value in the source alpha channel to set the destination pixel, useful for visualizing overdraw. - paint
Paintcontrols options applied when drawing.Paintcollects all options outside of thecrate::Canvasclip andcrate::Canvasmatrix.- 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::PathEffectthat stamps the given path at each lattice point of the transformed path. - path_
builder - Helper to build a
crate::Pathincrementally by adding verbs, with a more convenient API thancrate::Pathitself. - path_
effect - Base class for objects in a
crate::Paintthat 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.
- Generating PDF (Portable Document Format) output via Skia’s PDF backend (see
crate::Document). - perlin_
noise_ shader Deprecated - Deprecated factory functions for Perlin noise shaders, use
crate::shaders::fractal_noise()andcrate::shaders::turbulence()instead. - picture_
recorder - Records drawing commands into a
crate::Picturevia acrate::Canvas. - png_
encoder - Encoding of images into the PNG format, with configurable filtering and compression.
- recorder
- The
Recordertrait andRecorderReffor recording drawing commands, implemented by e.g.crate::cpu::Recorder. - region
- Describes the set of pixels used to clip
crate::Canvas.Regionis compact, efficiently storing a single integer rectangle, or a run length encoded array of rectangles.Regionmay reduce the currentcrate::Canvasclip, or may be drawn as one or more integer rectangles. TheRegioniterator 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
RRectdescribes: 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 andcrate::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::Painthas no shader, the paint’s color is used. - shader_
mask_ filter - Deprecated factory function for creating a
crate::MaskFilterfrom acrate::Shader. Shader mask filters will be removed in an upcoming Skia release. - shaders
- Shader factory functions and
Shaderconvenience constructors, re-exported fromcrate::shader::shaders. - skottie
- Skottie: rendering of Lottie (bodymovin) animations via Skia’s Skottie module (see [
Animation]). - stroke_
rec - Describes how a
crate::Pathis stroked: style, width, miter, cap, and join. - surface
- Describes a drawing destination: a
Surfacemanages the pixels or GPU resources that acrate::Canvasdraws into. - surfaces
- Factory functions for creating
crate::Surfaces, e.g. raster, null, and GPU-backed surfaces. - svg
- SVG (Scalable Vector Graphics) support: an SVG
Canvasand 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()andcrate::color_filters::table_argb()instead. - table_
mask_ filter - Deprecated
crate::MaskFilterfactory 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 theirCanvasequivalents. TheSkTiledImageUtilscalls will breakcrate::Bitmap-backedImages 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 theself::draw_image()/self::draw_image_rect()calls will fall through to the matchingCanvascall.- trim_
path_ effect - A
crate::PathEffectthat returns a subset of a path, given start and stoptvalues between 0 and 1. - typeface
- Describes the typeface and style of a font; a
Typefaceis used bycrate::Fontto 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::Pixmapplanes of a YUVA image:YUVAPixmapInfospecifies the plane layout,YUVAPixmapsstores 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
Canvasprovides an interface for drawing, and how the drawing is clipped and transformed.Canvascontains a stack ofMatrixand 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.Coloris the type used to specify colors incrate::Paintand in gradients. - Color4f
- Color
Channel Flag - Color
Space Primaries - Color
Space Transfer Fn - Cubic
Map - Fast evaluation of a cubic ease-in / ease-out curve. This is defined as a parametric cubic curve inside the unit square.
- Cubic
Resampler - Specify
bandc(each between 0…1) to create a shader that applies the corresponding cubic reconstruction filter to the image. - Date
Time - Document
- Filter
Options Deprecated - Font
Arguments - Represents a set of actual arguments for a font.
- Font
Metrics - Font
Style - Four
Byte Tag - HSV
- Handle
- Wraps a native type that can be represented in Rust memory.
- High
Contrast Config - Configuration struct for
ColorFilter::high_contrast(). - IPoint
- IRect
- ISize
- IVector
- Iter
- M44
- 4x4 matrix used by
crate::Canvasand other parts of Skia. - Matrix
- Owned
Canvas - Represents a
Canvasthat 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). - Path
Contour Iter - Path
Contour Iter Rec - Path
Iter - Path
Iter Rec - Path
Segment Mask - 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.
- Recorder
Ref - Rect
- RefHandle
- A wrapper type that represents a native type with a pointer to the native object.
- Sampling
Options - Sendable
- Size
- Surface
Props - 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).
- Surface
Props Flags - Text
Blob Run - V2
- V3
- V4
- XYZD50
Hash
Enums§
- Alpha
Type - Describes how to interpret the alpha component of a pixel. A pixel may be opaque, or alpha, describing multiple levels of transparency.
- Auto
Canvas Restore - Blend
Mode - 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.
- Blend
Mode Coeff - Blur
Style - ClipOp
- Codec
Result - Error codes for various
Codecmethods. - Color
Channel - Color
Type - Describes how pixel bits encode color. A pixel may be an alpha mask, a grayscale, RGB, or ARGB.
- Coverage
Mode - 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. - Encoded
Image Format - Enum describing format of encoded data.
- Filter
Mode - Mipmap
Mode - Paint
Cap Capdraws at the beginning and end of an open path contour.- Paint
Join Joinspecifies how corners are drawn when a shape is stroked.Joinaffects the four corners of a stroked rectangle, and the connected segments in a stroked path.- Paint
Style - Set the
Styleto 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. - Pixel
Geometry - 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. - Text
Encoding - Texture
Compression Type - Skia | GL_COMPRESSED_* | MTLPixelFormat* | VK_FORMAT_*_BLOCK
- Tile
Mode - Describes how a shader draws outside of its original bounds:
TileMode::Clampreplicates the edge color,TileMode::Repeatrepeats the image horizontally and vertically,TileMode::Mirrorrepeats the image with alternating mirror images so adjacent images always seam, andTileMode::Decaldraws only within the original domain, returning transparent-black everywhere else. - YUVColor
Space
Constants§
Traits§
- Conditionally
Send - Contains
- Encoded
Text - Trait representing encoded text.
- Flattenable
- Native
Flattenable - Pixel
- Implement this trait to use a pixel type in
Handle<Pixmap>::pixels(). - Quick
Reject - Recorder
- Round
Out - 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
oneandtwo: 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
PMColorvalue from unpremultiplied 8-bit component values. - pre_
multiply_ color - Returns the premultiplied color closest to
c. Multiplies thecRGB components by thecalpha, and arranges the bytes to match the format ofcrate::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_
bounds Deprecated - Set the resulting rectangle to the tight bounds of the path.
Type Aliases§
- BBHFactory
- BBox
Hierarchy - Bitmap
Bitmapdescribes a two-dimensional raster pixel array.Bitmapis built onImageInfo, containing integer width and height,ColorTypeandAlphaTypedescribing the pixel format, andColorSpacedescribing the range of colors.Bitmappoints toPixelRef, which describes the physical array of pixels.ImageInfobounds may be located anywhere fully insidePixelRefbounds.- Blender
Blenderrepresents 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
- Color
Filter - Color
Info - Describes pixel and encoding.
ImageInfocan be created fromColorInfoby providing dimensions. - Color
Matrix - Color
Space - Color
Table ColorTableholds the lookup tables for each channel (ARGB) used to define the filter behavior ofSkColorFilters::Table, and provides a way to share the table data between client code and the returnedcrate::ColorFilter. Once created, anColorTableis immutable.- Context
- Skia’s central context object for shared resources and internal caches.
- Context
Options - Options shared by Skia’s raster and GPU context factories.
- Contour
Measure - Contour
Measure Iter - Data
- Data
Table - Like
crate::Data,DataTableholds 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
Fontcontrols options applied when drawing and measuring text.- Font
Hinting - FontMgr
- Font
Style Set - GlyphId
- Image
Imagedescribes a two dimensional array of pixels to draw. The pixels may be decoded in a raster bitmap, encoded in aPictureor compressed data stream, or located in GPU memory as a GPU texture.- Image
Filter - Image
Generator - Image
Info - Describes pixel dimensions and encoding.
crate::Bitmap,crate::Image,crate::Pixmap, andcrate::Surfacecan be created fromImageInfo.ImageInfocan be retrieved fromcrate::Bitmapandcrate::Pixmap, but not fromcrate::Imageandcrate::Surface. For example,crate::Imageandcrate::Surfaceimplementations may defer pixel depth, so may not completely specifyImageInfo. - Mask
Filter - 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. - Mesh
Specification - 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
Paintcontrols options applied when drawing.- Path
Pathcontain geometry.Pathmay be empty, or contain one or more verbs that outline a figure.Pathalways 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.Pathmay contain any number of contours, each beginning with a move verb.- Path
Builder - Path
Direction - Path
Effect - Path
Fill Type - Path
Measure - PathOp
- The logical operations that can be performed when combining two paths.
- Path
Verb - Picture
- Picture
Recorder - Pixel
Ref - Region
- Runtime
Effect RuntimeEffectsupports creating customShaderandColorFilterobjects using Skia’s SkSL shading language.- Sampling
Mode Deprecated - Shader
- Strike
Ref StrikeRefis a lightweight, thread-safe handle to a resolved font strike.- Stroke
Rec - Surface
Surfaceis 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 (aRenderTargetsurface).Surfacetakes care of allocating aCanvasthat will draw into the surface. CallSurface::canvas()to use that canvas (but don’t delete it, it is owned by the surface).Surfacealways has non-zero dimensions. If there is a request for a new surface, and either of the requested dimensions are zero, thenNonewill be returned.- Text
Blob - Text
Blob Builder - Helper class for constructing
TextBlob. - Text
Blob Iter - Typeface
- Unichar
- Vector
- Vector3
- Vertices
- An immutable set of vertex data that can be used with
crate::Canvas::draw_vertices. - 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 YUVAInfocombined with per-planeColorTypes and row bytes. Fully specifies thePixmap`s for a YUVA image without the actual pixel memory and data.- YUVA
Pixmaps - Helper to store
Pixmapplanes as described by aYUVAPixmapInfo. Can be responsible for allocating/freeing memory for pixmaps or use external memory. - scalar