skia_safe/core/canvas.rs
1//! [`Canvas`] provides an interface for drawing, and how the drawing is clipped and transformed.
2//! [`Canvas`] contains a stack of [`crate::Matrix`] and clip values.
3
4use std::{cell::UnsafeCell, ffi::CString, fmt, marker::PhantomData, mem, ops::Deref, ptr, slice};
5
6use sb::SkCanvas_FilterSpan;
7use skia_bindings::{
8 self as sb, SkAutoCanvasRestore, SkCanvas, SkCanvas_SaveLayerRec, SkColorSpace, SkImageFilter,
9 SkPaint, SkRect, U8CPU,
10};
11
12#[cfg(feature = "graphite")]
13use crate::gpu::graphite;
14#[cfg(feature = "ganesh")]
15use crate::gpu::{DirectContext, RecordingContext};
16use crate::{Arc, ColorSpace};
17use crate::{
18 Bitmap, BlendMode, ClipOp, Color, Color4f, Data, Drawable, FilterMode, Font, GlyphId, IPoint,
19 IRect, ISize, Image, ImageFilter, ImageInfo, M44, Matrix, Paint, Path, Picture, Pixmap, Point,
20 QuickReject, RRect, RSXform, Rect, Region, SamplingOptions, Shader, Surface, SurfaceProps,
21 TextBlob, TextEncoding, TileMode, Vector, Vertices, prelude::*, scalar,
22};
23
24pub use lattice::Lattice;
25
26bitflags! {
27 /// [`SaveLayerFlags`] provides options that may be used in any combination in [`SaveLayerRec`],
28 /// defining how layer allocated by [`Canvas::save_layer()`] operates. It may be set to zero,
29 /// [`PRESERVE_LCD_TEXT`], [`INIT_WITH_PREVIOUS`], or both flags.
30 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
31 pub struct SaveLayerFlags: u32 {
32 const PRESERVE_LCD_TEXT = sb::SkCanvas_SaveLayerFlagsSet_kPreserveLCDText_SaveLayerFlag as _;
33 /// initializes with previous contents
34 const INIT_WITH_PREVIOUS = sb::SkCanvas_SaveLayerFlagsSet_kInitWithPrevious_SaveLayerFlag as _;
35 const F16_COLOR_TYPE = sb::SkCanvas_SaveLayerFlagsSet_kF16ColorType as _;
36 }
37}
38
39/// [`SaveLayerRec`] contains the state used to create the layer.
40#[repr(C)]
41pub struct SaveLayerRec<'a> {
42 // We _must_ store _references_ to the native types here, because not all of them are native
43 // transmutable, like ImageFilter or Image, which are represented as ref counted pointers and so
44 // we would store a reference to a pointer only.
45 bounds: Option<&'a SkRect>,
46 paint: Option<&'a SkPaint>,
47 filters: SkCanvas_FilterSpan,
48 backdrop: Option<&'a SkImageFilter>,
49 backdrop_tile_mode: sb::SkTileMode,
50 color_space: Option<&'a SkColorSpace>,
51 flags: SaveLayerFlags,
52 experimental_backdrop_scale: scalar,
53}
54
55native_transmutable!(SkCanvas_SaveLayerRec, SaveLayerRec<'_>);
56
57impl Default for SaveLayerRec<'_> {
58 /// Sets [`Self::bounds`], [`Self::paint`], and [`Self::backdrop`] to `None`. Clears
59 /// [`Self::flags`].
60 ///
61 /// Returns empty [`SaveLayerRec`]
62 fn default() -> Self {
63 SaveLayerRec::construct(|slr| unsafe { sb::C_SkCanvas_SaveLayerRec_Construct(slr) })
64 }
65}
66
67impl Drop for SaveLayerRec<'_> {
68 fn drop(&mut self) {
69 unsafe { sb::C_SkCanvas_SaveLayerRec_destruct(self.native_mut()) }
70 }
71}
72
73impl fmt::Debug for SaveLayerRec<'_> {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.debug_struct("SaveLayerRec")
76 .field("bounds", &self.bounds.map(Rect::from_native_ref))
77 .field("paint", &self.paint.map(Paint::from_native_ref))
78 .field(
79 "backdrop",
80 &ImageFilter::from_unshared_ptr_ref(&(self.backdrop.as_ptr_or_null() as *mut _)),
81 )
82 .field("backdrop_tile_mode", &self.backdrop_tile_mode)
83 .field(
84 "color_space",
85 &ColorSpace::from_unshared_ptr_ref(&(self.color_space.as_ptr_or_null() as *mut _)),
86 )
87 .field("flags", &self.flags)
88 .field(
89 "experimental_backdrop_scale",
90 &self.experimental_backdrop_scale,
91 )
92 .finish()
93 }
94}
95
96impl<'a> SaveLayerRec<'a> {
97 /// Hints at layer size limit
98 #[must_use]
99 pub fn bounds(mut self, bounds: &'a Rect) -> Self {
100 self.bounds = Some(bounds.native());
101 self
102 }
103
104 /// Modifies overlay
105 #[must_use]
106 pub fn paint(mut self, paint: &'a Paint) -> Self {
107 self.paint = Some(paint.native());
108 self
109 }
110
111 /// If not `None`, this triggers the same initialization behavior as setting
112 /// [`SaveLayerFlags::INIT_WITH_PREVIOUS`] on [`Self::flags`]: the current layer is copied into
113 /// the new layer, rather than initializing the new layer with transparent-black. This is then
114 /// filtered by [`Self::backdrop`] (respecting the current clip).
115 #[must_use]
116 pub fn backdrop(mut self, backdrop: &'a ImageFilter) -> Self {
117 self.backdrop = Some(backdrop.native());
118 self
119 }
120
121 /// If the layer is initialized with prior content (and/or with a backdrop filter) and this
122 /// would require sampling outside of the available backdrop, this is the tilemode applied
123 /// to the boundary of the prior layer's image.
124 #[must_use]
125 pub fn backdrop_tile_mode(mut self, backdrop_tile_mode: TileMode) -> Self {
126 self.backdrop_tile_mode = backdrop_tile_mode;
127 self
128 }
129
130 /// If not `None`, this triggers a color space conversion when the layer is restored. It
131 /// will be as if the layer's contents are drawn in this color space. Filters from
132 /// `backdrop` and `paint` will be applied in this color space.
133 pub fn color_space(mut self, color_space: &'a ColorSpace) -> Self {
134 self.color_space = Some(color_space.native());
135 self
136 }
137
138 /// Preserves LCD text, creates with prior layer contents
139 #[must_use]
140 pub fn flags(mut self, flags: SaveLayerFlags) -> Self {
141 self.flags = flags;
142 self
143 }
144}
145
146/// Selects if an array of points are drawn as discrete points, as lines, or as an open polygon.
147pub use sb::SkCanvas_PointMode as PointMode;
148variant_name!(PointMode::Polygon);
149
150/// [`SrcRectConstraint`] controls the behavior at the edge of source [`Rect`], provided to
151/// [`Canvas::draw_image_rect()`] when there is any filtering. If kStrict is set, then extra code is
152/// used to ensure it nevers samples outside of the src-rect.
153///
154/// [`SrcRectConstraint::Strict`] disables the use of mipmaps and anisotropic filtering.
155pub use sb::SkCanvas_SrcRectConstraint as SrcRectConstraint;
156variant_name!(SrcRectConstraint::Fast);
157
158/// Provides access to Canvas's pixels.
159///
160/// Returned by [`Canvas::access_top_layer_pixels()`]
161#[derive(Debug)]
162pub struct TopLayerPixels<'a> {
163 /// Address of pixels
164 pub pixels: &'a mut [u8],
165 /// Writable pixels' [`ImageInfo`]
166 pub info: ImageInfo,
167 /// Writable pixels' row bytes
168 pub row_bytes: usize,
169 /// [`Canvas`] top layer origin, its top-left corner
170 pub origin: IPoint,
171}
172
173/// Used to pass either a slice of [`Point`] or [`RSXform`] to [`Canvas::draw_glyphs_at`].
174#[derive(Clone, Debug)]
175pub enum GlyphPositions<'a> {
176 Points(&'a [Point]),
177 RSXforms(&'a [RSXform]),
178}
179
180impl<'a> From<&'a [Point]> for GlyphPositions<'a> {
181 fn from(points: &'a [Point]) -> Self {
182 Self::Points(points)
183 }
184}
185
186impl<'a> From<&'a [RSXform]> for GlyphPositions<'a> {
187 fn from(rs_xforms: &'a [RSXform]) -> Self {
188 Self::RSXforms(rs_xforms)
189 }
190}
191
192/// [`Canvas`] provides an interface for drawing, and how the drawing is clipped and transformed.
193/// [`Canvas`] contains a stack of [`Matrix`] and clip values.
194///
195/// [`Canvas`] and [`Paint`] together provide the state to draw into [`Surface`] or `Device`.
196/// Each [`Canvas`] draw call transforms the geometry of the object by the concatenation of all
197/// [`Matrix`] values in the stack. The transformed geometry is clipped by the intersection
198/// of all of clip values in the stack. The [`Canvas`] draw calls use [`Paint`] to supply drawing
199/// state such as color, [`crate::Typeface`], text size, stroke width, [`Shader`] and so on.
200///
201/// To draw to a pixel-based destination, create raster surface or GPU surface.
202/// Request [`Canvas`] from [`Surface`] to obtain the interface to draw.
203/// [`Canvas`] generated by raster surface draws to memory visible to the CPU.
204/// [`Canvas`] generated by GPU surface uses Vulkan or OpenGL to draw to the GPU.
205///
206/// To draw to a document, obtain [`Canvas`] from SVG canvas, document PDF, or
207/// [`crate::PictureRecorder`]. [`crate::Document`] based [`Canvas`] and other [`Canvas`]
208/// subclasses reference Device describing the destination.
209///
210/// [`Canvas`] can be constructed to draw to [`Bitmap`] without first creating raster surface.
211/// This approach may be deprecated in the future.
212#[repr(transparent)]
213pub struct Canvas(UnsafeCell<SkCanvas>);
214
215impl Canvas {
216 pub(self) fn native(&self) -> &SkCanvas {
217 unsafe { &*self.0.get() }
218 }
219
220 #[allow(clippy::mut_from_ref)]
221 pub(crate) fn native_mut(&self) -> &mut SkCanvas {
222 unsafe { &mut (*self.0.get()) }
223 }
224}
225
226impl fmt::Debug for Canvas {
227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228 f.debug_struct("Canvas")
229 .field("image_info", &self.image_info())
230 .field("props", &self.props())
231 .field("base_layer_size", &self.base_layer_size())
232 .field("save_count", &self.save_count())
233 .field("local_clip_bounds", &self.local_clip_bounds())
234 .field("device_clip_bounds", &self.device_clip_bounds())
235 .field("local_to_device", &self.local_to_device())
236 .finish()
237 }
238}
239
240/// Represents a [`Canvas`] that is owned and dropped when it goes out of scope _and_ is bound to
241/// the lifetime of some other value (an array of pixels for example).
242///
243/// Access to the [`Canvas`] functions are resolved with the [`Deref`] trait.
244#[repr(transparent)]
245pub struct OwnedCanvas<'lt>(ptr::NonNull<Canvas>, PhantomData<&'lt ()>);
246
247impl Deref for OwnedCanvas<'_> {
248 type Target = Canvas;
249
250 fn deref(&self) -> &Self::Target {
251 unsafe { self.0.as_ref() }
252 }
253}
254
255impl Drop for OwnedCanvas<'_> {
256 /// Draws saved layers, if any.
257 /// Frees up resources used by [`Canvas`].
258 ///
259 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_destructor>
260 fn drop(&mut self) {
261 unsafe { sb::C_SkCanvas_delete(self.native()) }
262 }
263}
264
265impl Default for OwnedCanvas<'_> {
266 /// Creates an empty [`Canvas`] with no backing device or pixels, with
267 /// a width and height of zero.
268 ///
269 /// Returns empty [`Canvas`]
270 ///
271 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_empty_constructor>
272 fn default() -> Self {
273 let ptr = unsafe { sb::C_SkCanvas_newEmpty() };
274 Canvas::own_from_native_ptr(ptr).unwrap()
275 }
276}
277
278impl fmt::Debug for OwnedCanvas<'_> {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 f.debug_tuple("OwnedCanvas").field(self as &Canvas).finish()
281 }
282}
283
284impl Canvas {
285 /// Allocates raster [`Canvas`] that will draw directly into pixels.
286 ///
287 /// [`Canvas`] is returned if all parameters are valid.
288 /// Valid parameters include:
289 /// - `info` dimensions are zero or positive
290 /// - `info` contains [`crate::ColorType`] and [`crate::AlphaType`] supported by raster surface
291 /// - `row_bytes` is `None` or large enough to contain info width pixels of [`crate::ColorType`]
292 ///
293 /// Pass `None` for `row_bytes` to compute `row_bytes` from info width and size of pixel.
294 /// If `row_bytes` is not `None`, it must be equal to or greater than `info` width times
295 /// bytes required for [`crate::ColorType`].
296 ///
297 /// Pixel buffer size should be info height times computed `row_bytes`.
298 /// Pixels are not initialized.
299 /// To access pixels after drawing, call `flush()` or [`Self::peek_pixels()`].
300 ///
301 /// - `info` width, height, [`crate::ColorType`], [`crate::AlphaType`], [`crate::ColorSpace`],
302 /// of raster surface; width, or height, or both, may be zero
303 /// - `pixels` pointer to destination pixels buffer
304 /// - `row_bytes` interval from one [`Surface`] row to the next, or zero
305 /// - `props` LCD striping orientation and setting for device independent fonts;
306 /// may be `None`
307 ///
308 /// Returns [`OwnedCanvas`] if all parameters are valid; otherwise, `None`.
309 pub fn from_raster_direct<'pixels>(
310 info: &ImageInfo,
311 pixels: &'pixels mut [u8],
312 row_bytes: impl Into<Option<usize>>,
313 props: Option<&SurfaceProps>,
314 ) -> Option<OwnedCanvas<'pixels>> {
315 let row_bytes = row_bytes.into().unwrap_or_else(|| info.min_row_bytes());
316 if info.valid_pixels(row_bytes, pixels) {
317 let ptr = unsafe {
318 sb::C_SkCanvas_MakeRasterDirect(
319 info.native(),
320 pixels.as_mut_ptr() as _,
321 row_bytes,
322 props.native_ptr_or_null(),
323 )
324 };
325 Self::own_from_native_ptr(ptr)
326 } else {
327 None
328 }
329 }
330
331 /// Allocates raster [`Canvas`] specified by inline image specification. Subsequent [`Canvas`]
332 /// calls draw into pixels.
333 /// [`crate::ColorType`] is set to [`crate::ColorType::n32()`].
334 /// [`crate::AlphaType`] is set to [`crate::AlphaType::Premul`].
335 /// To access pixels after drawing, call `flush()` or [`Self::peek_pixels()`].
336 ///
337 /// [`OwnedCanvas`] is returned if all parameters are valid.
338 /// Valid parameters include:
339 /// - width and height are zero or positive
340 /// - `row_bytes` is zero or large enough to contain width pixels of [`crate::ColorType::n32()`]
341 ///
342 /// Pass `None` for `row_bytes` to compute `row_bytes` from width and size of pixel.
343 /// If `row_bytes` is greater than zero, it must be equal to or greater than width times bytes
344 /// required for [`crate::ColorType`].
345 ///
346 /// Pixel buffer size should be height times `row_bytes`.
347 ///
348 /// - `size` pixel column and row count on raster surface created; must both be zero or greater
349 /// - `pixels` pointer to destination pixels buffer; buffer size should be height times
350 /// `row_bytes`
351 /// - `row_bytes` interval from one [`Surface`] row to the next, or zero
352 ///
353 /// Returns [`OwnedCanvas`] if all parameters are valid; otherwise, `None`
354 pub fn from_raster_direct_n32<'pixels>(
355 size: impl Into<ISize>,
356 pixels: &'pixels mut [u32],
357 row_bytes: impl Into<Option<usize>>,
358 ) -> Option<OwnedCanvas<'pixels>> {
359 let info = ImageInfo::new_n32_premul(size, None);
360 let pixels_ptr: *mut u8 = pixels.as_mut_ptr() as _;
361 let pixels_u8: &'pixels mut [u8] =
362 unsafe { slice::from_raw_parts_mut(pixels_ptr, mem::size_of_val(pixels)) };
363 Self::from_raster_direct(&info, pixels_u8, row_bytes, None)
364 }
365
366 /// Creates [`Canvas`] of the specified dimensions without a [`Surface`].
367 /// Used by subclasses with custom implementations for draw member functions.
368 ///
369 /// If props equals `None`, [`SurfaceProps`] are created with `SurfaceProps::InitType` settings,
370 /// which choose the pixel striping direction and order. Since a platform may dynamically change
371 /// its direction when the device is rotated, and since a platform may have multiple monitors
372 /// with different characteristics, it is best not to rely on this legacy behavior.
373 ///
374 /// - `size` with and height zero or greater
375 /// - `props` LCD striping orientation and setting for device independent fonts;
376 /// may be `None`
377 ///
378 /// Returns [`Canvas`] placeholder with dimensions
379 ///
380 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_int_int_const_SkSurfaceProps_star>
381 #[allow(clippy::new_ret_no_self)]
382 pub fn new<'lt>(
383 size: impl Into<ISize>,
384 props: Option<&SurfaceProps>,
385 ) -> Option<OwnedCanvas<'lt>> {
386 let size = size.into();
387 if size.width >= 0 && size.height >= 0 {
388 let ptr = unsafe {
389 sb::C_SkCanvas_newWidthHeightAndProps(
390 size.width,
391 size.height,
392 props.native_ptr_or_null(),
393 )
394 };
395 Canvas::own_from_native_ptr(ptr)
396 } else {
397 None
398 }
399 }
400
401 /// Constructs a canvas that draws into bitmap.
402 /// Use props to match the device characteristics, like LCD striping.
403 ///
404 /// bitmap is copied so that subsequently editing bitmap will not affect constructed [`Canvas`].
405 ///
406 /// - `bitmap` width, height, [`crate::ColorType`], [`crate::AlphaType`], and pixel storage of
407 /// raster surface
408 /// - `props` order and orientation of RGB striping; and whether to use device independent fonts
409 ///
410 /// Returns [`Canvas`] that can be used to draw into bitmap
411 ///
412 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_copy_const_SkBitmap>
413 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_const_SkBitmap_const_SkSurfaceProps>
414 pub fn from_bitmap<'lt>(
415 bitmap: &Bitmap,
416 props: Option<&SurfaceProps>,
417 ) -> Option<OwnedCanvas<'lt>> {
418 // <https://github.com/rust-skia/rust-skia/issues/669>
419 if !bitmap.is_ready_to_draw() {
420 return None;
421 }
422 let props_ptr = props.native_ptr_or_null();
423 let ptr = if props_ptr.is_null() {
424 unsafe { sb::C_SkCanvas_newFromBitmap(bitmap.native()) }
425 } else {
426 unsafe { sb::C_SkCanvas_newFromBitmapAndProps(bitmap.native(), props_ptr) }
427 };
428 Canvas::own_from_native_ptr(ptr)
429 }
430
431 /// Returns [`ImageInfo`] for [`Canvas`]. If [`Canvas`] is not associated with raster surface or
432 /// GPU surface, returned [`crate::ColorType`] is set to [`crate::ColorType::Unknown`]
433 ///
434 /// Returns dimensions and [`crate::ColorType`] of [`Canvas`]
435 ///
436 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_imageInfo>
437 pub fn image_info(&self) -> ImageInfo {
438 let mut ii = ImageInfo::default();
439 unsafe { sb::C_SkCanvas_imageInfo(self.native(), ii.native_mut()) };
440 ii
441 }
442
443 /// Copies [`SurfaceProps`], if [`Canvas`] is associated with raster surface or GPU surface, and
444 /// returns `true`. Otherwise, returns `false` and leave props unchanged.
445 ///
446 /// - `props` storage for writable [`SurfaceProps`]
447 ///
448 /// Returns `true` if [`SurfaceProps`] was copied
449 ///
450 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_getProps>
451 pub fn props(&self) -> Option<SurfaceProps> {
452 let mut sp = SurfaceProps::default();
453 unsafe { self.native().getProps(sp.native_mut()) }.then_some(sp)
454 }
455
456 /// Returns the [`SurfaceProps`] associated with the canvas (i.e., at the base of the layer
457 /// stack).
458 pub fn base_props(&self) -> SurfaceProps {
459 SurfaceProps::from_native_c(unsafe { self.native().getBaseProps() })
460 }
461
462 /// Returns the [`SurfaceProps`] associated with the canvas that are currently active (i.e., at
463 /// the top of the layer stack). This can differ from [`Self::base_props`] depending on the flags
464 /// passed to saveLayer (see [`SaveLayerFlags`]).
465 pub fn top_props(&self) -> SurfaceProps {
466 SurfaceProps::from_native_c(unsafe { self.native().getTopProps() })
467 }
468
469 /// Gets the size of the base or root layer in global canvas coordinates. The
470 /// origin of the base layer is always (0,0). The area available for drawing may be
471 /// smaller (due to clipping or saveLayer).
472 ///
473 /// Returns integral size of base layer
474 ///
475 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_getBaseLayerSize>
476 pub fn base_layer_size(&self) -> ISize {
477 let mut size = ISize::default();
478 unsafe { sb::C_SkCanvas_getBaseLayerSize(self.native(), size.native_mut()) }
479 size
480 }
481
482 /// Creates [`Surface`] matching info and props, and associates it with [`Canvas`].
483 /// Returns `None` if no match found.
484 ///
485 /// If props is `None`, matches [`SurfaceProps`] in [`Canvas`]. If props is `None` and
486 /// [`Canvas`] does not have [`SurfaceProps`], creates [`Surface`] with default
487 /// [`SurfaceProps`].
488 ///
489 /// - `info` width, height, [`crate::ColorType`], [`crate::AlphaType`], and
490 /// [`crate::ColorSpace`]
491 /// - `props` [`SurfaceProps`] to match; may be `None` to match [`Canvas`]
492 ///
493 /// Returns [`Surface`] matching info and props, or `None` if no match is available
494 ///
495 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_makeSurface>
496 pub fn new_surface(&self, info: &ImageInfo, props: Option<&SurfaceProps>) -> Option<Surface> {
497 Surface::from_ptr(unsafe {
498 sb::C_SkCanvas_makeSurface(self.native_mut(), info.native(), props.native_ptr_or_null())
499 })
500 }
501
502 /// Returns Ganesh context of the GPU surface associated with [`Canvas`].
503 ///
504 /// Returns GPU context, if available; `None` otherwise
505 ///
506 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_recordingContext>
507 #[cfg(feature = "ganesh")]
508 pub fn recording_context(&self) -> Option<RecordingContext> {
509 RecordingContext::from_unshared_ptr(unsafe {
510 sb::C_SkCanvas_recordingContext(self.native())
511 })
512 }
513
514 /// Returns the [`DirectContext`].
515 /// This is a rust-skia helper for that makes it simpler to call [`Image::encode`].
516 #[cfg(feature = "ganesh")]
517 pub fn direct_context(&self) -> Option<DirectContext> {
518 self.recording_context()
519 .and_then(|mut c| c.as_direct_context())
520 }
521
522 /// Returns the [`graphite::Recorder`] for the GPU surface backing this
523 /// canvas, if it is Graphite-backed.
524 ///
525 /// [`Canvas::recorder()`] returns a *borrowed* pointer — the recorder is
526 /// owned by the surface/canvas — so the result is a
527 /// [`graphite::BorrowedRecorder`] that does not delete the recorder on drop
528 /// and is bound to this canvas's lifetime. Wrapping it in an owning handle
529 /// would double-free the recorder.
530 #[cfg(feature = "graphite")]
531 pub fn recorder(&self) -> Option<graphite::BorrowedRecorder<'_>> {
532 let recorder =
533 graphite::Recorder::from_ptr(unsafe { sb::C_SkCanvas_recorder(self.native()) })?;
534 Some(graphite::BorrowedRecorder::from_canvas(recorder, self))
535 }
536
537 /// Sometimes a canvas is owned by a surface. If it is, [`Self::surface()`] will return a bare
538 /// pointer to that surface, else this will return `None`.
539 ///
540 /// # Safety
541 /// This function is unsafe because it is not clear how exactly the lifetime of the canvas
542 /// relates to surface returned.
543 /// See also [`OwnedCanvas`], [`RCHandle<SkSurface>::canvas()`].
544 pub unsafe fn surface(&self) -> Option<Surface> {
545 unsafe {
546 // TODO: It might be possible to make this safe by returning a _kind of_ reference to the
547 // Surface that can not be cloned and stays bound to the lifetime of canvas.
548 // But even then, the Surface might exist twice then, which is confusing, but
549 // probably safe, because the first instance is borrowed by the canvas.
550 Surface::from_unshared_ptr(self.native().getSurface())
551 }
552 }
553
554 /// Returns the pixel base address, [`ImageInfo`], `row_bytes`, and origin if the pixels
555 /// can be read directly.
556 ///
557 /// - `info` storage for writable pixels' [`ImageInfo`]
558 /// - `row_bytes` storage for writable pixels' row bytes
559 /// - `origin` storage for [`Canvas`] top layer origin, its top-left corner
560 ///
561 /// Returns address of pixels, or `None` if inaccessible
562 ///
563 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_accessTopLayerPixels_a>
564 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_accessTopLayerPixels_b>
565 pub fn access_top_layer_pixels(&self) -> Option<TopLayerPixels> {
566 let mut info = ImageInfo::default();
567 let mut row_bytes = 0;
568 let mut origin = IPoint::default();
569 let ptr = unsafe {
570 self.native_mut().accessTopLayerPixels(
571 info.native_mut(),
572 &mut row_bytes,
573 origin.native_mut(),
574 )
575 };
576 if !ptr.is_null() {
577 let size = info.compute_byte_size(row_bytes);
578 let pixels = unsafe { slice::from_raw_parts_mut(ptr as _, size) };
579 Some(TopLayerPixels {
580 pixels,
581 info,
582 row_bytes,
583 origin,
584 })
585 } else {
586 None
587 }
588 }
589
590 // TODO: accessTopRasterHandle()
591
592 /// Returns `true` if [`Canvas`] has direct access to its pixels.
593 ///
594 /// Pixels are readable when `Device` is raster. Pixels are not readable when [`Canvas`] is
595 /// returned from GPU surface, returned by [`crate::Document::begin_page()`], returned by
596 /// [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a utility
597 /// class like `DebugCanvas`.
598 ///
599 /// pixmap is valid only while [`Canvas`] is in scope and unchanged. Any [`Canvas`] or
600 /// [`Surface`] call may invalidate the pixmap values.
601 ///
602 /// Returns [`Pixmap`] if [`Canvas`] has direct access to pixels
603 ///
604 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_peekPixels>
605 pub fn peek_pixels(&self) -> Option<Pixmap> {
606 let mut pixmap = Pixmap::default();
607 unsafe { self.native_mut().peekPixels(pixmap.native_mut()) }.then_some(pixmap)
608 }
609
610 /// Copies [`Rect`] of pixels from [`Canvas`] into `dst_pixels`. [`Matrix`] and clip are
611 /// ignored.
612 ///
613 /// Source [`Rect`] corners are `src_point` and `(image_info().width(), image_info().height())`.
614 /// Destination [`Rect`] corners are `(0, 0)` and `(dst_Info.width(), dst_info.height())`.
615 /// Copies each readable pixel intersecting both rectangles, without scaling,
616 /// converting to `dst_info.color_type()` and `dst_info.alpha_type()` if required.
617 ///
618 /// Pixels are readable when `Device` is raster, or backed by a GPU.
619 /// Pixels are not readable when [`Canvas`] is returned by [`crate::Document::begin_page()`],
620 /// returned by [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a
621 /// utility class like `DebugCanvas`.
622 ///
623 /// The destination pixel storage must be allocated by the caller.
624 ///
625 /// Pixel values are converted only if [`crate::ColorType`] and [`crate::AlphaType`]
626 /// do not match. Only pixels within both source and destination rectangles
627 /// are copied. `dst_pixels` contents outside [`Rect`] intersection are unchanged.
628 ///
629 /// Pass negative values for `src_point.x` or `src_point.y` to offset pixels across or down
630 /// destination.
631 ///
632 /// Does not copy, and returns `false` if:
633 /// - Source and destination rectangles do not intersect.
634 /// - [`Canvas`] pixels could not be converted to `dst_info.color_type()` or
635 /// `dst_info.alpha_type()`.
636 /// - [`Canvas`] pixels are not readable; for instance, [`Canvas`] is document-based.
637 /// - `dst_row_bytes` is too small to contain one row of pixels.
638 ///
639 /// - `dst_info` width, height, [`crate::ColorType`], and [`crate::AlphaType`] of dstPixels
640 /// - `dst_pixels` storage for pixels; `dst_info.height()` times `dst_row_bytes`, or larger
641 /// - `dst_row_bytes` size of one destination row; `dst_info.width()` times pixel size, or
642 /// larger
643 /// - `src_point` offset into readable pixels; may be negative
644 ///
645 /// Returns `true` if pixels were copied
646 #[must_use]
647 pub fn read_pixels(
648 &self,
649 dst_info: &ImageInfo,
650 dst_pixels: &mut [u8],
651 dst_row_bytes: usize,
652 src_point: impl Into<IPoint>,
653 ) -> bool {
654 let src_point = src_point.into();
655 let required_size = dst_info.compute_byte_size(dst_row_bytes);
656 (dst_pixels.len() >= required_size)
657 && unsafe {
658 self.native_mut().readPixels(
659 dst_info.native(),
660 dst_pixels.as_mut_ptr() as _,
661 dst_row_bytes,
662 src_point.x,
663 src_point.y,
664 )
665 }
666 }
667
668 /// Copies [`Rect`] of pixels from [`Canvas`] into pixmap. [`Matrix`] and clip are
669 /// ignored.
670 ///
671 /// Source [`Rect`] corners are `(src.x, src.y)` and `(image_info().width(),
672 /// image_info().height())`.
673 /// Destination [`Rect`] corners are `(0, 0)` and `(pixmap.width(), pixmap.height())`.
674 /// Copies each readable pixel intersecting both rectangles, without scaling,
675 /// converting to `pixmap.color_type()` and `pixmap.alpha_type()` if required.
676 ///
677 /// Pixels are readable when `Device` is raster, or backed by a GPU. Pixels are not readable
678 /// when [`Canvas`] is returned by [`crate::Document::begin_page()`], returned by
679 /// [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a utility
680 /// class like `DebugCanvas`.
681 ///
682 /// Caller must allocate pixel storage in pixmap if needed.
683 ///
684 /// Pixel values are converted only if [`crate::ColorType`] and [`crate::AlphaType`] do not
685 /// match. Only pixels within both source and destination [`Rect`] are copied. pixmap pixels
686 /// contents outside [`Rect`] intersection are unchanged.
687 ///
688 /// Pass negative values for `src.x` or `src.y` to offset pixels across or down pixmap.
689 ///
690 /// Does not copy, and returns `false` if:
691 /// - Source and destination rectangles do not intersect.
692 /// - [`Canvas`] pixels could not be converted to `pixmap.color_type()` or
693 /// `pixmap.alpha_type()`.
694 /// - [`Canvas`] pixels are not readable; for instance, [`Canvas`] is document-based.
695 /// - [`Pixmap`] pixels could not be allocated.
696 /// - `pixmap.row_bytes()` is too small to contain one row of pixels.
697 ///
698 /// - `pixmap` storage for pixels copied from [`Canvas`]
699 /// - `src` offset into readable pixels ; may be negative
700 ///
701 /// Returns `true` if pixels were copied
702 ///
703 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_readPixels_2>
704 #[must_use]
705 pub fn read_pixels_to_pixmap(&self, pixmap: &mut Pixmap, src: impl Into<IPoint>) -> bool {
706 let src = src.into();
707 unsafe { self.native_mut().readPixels1(pixmap.native(), src.x, src.y) }
708 }
709
710 /// Copies [`Rect`] of pixels from [`Canvas`] into bitmap. [`Matrix`] and clip are
711 /// ignored.
712 ///
713 /// Source [`Rect`] corners are `(src.x, src.y)` and `(image_info().width(),
714 /// image_info().height())`.
715 /// Destination [`Rect`] corners are `(0, 0)` and `(bitmap.width(), bitmap.height())`.
716 /// Copies each readable pixel intersecting both rectangles, without scaling,
717 /// converting to `bitmap.color_type()` and `bitmap.alpha_type()` if required.
718 ///
719 /// Pixels are readable when `Device` is raster, or backed by a GPU. Pixels are not readable
720 /// when [`Canvas`] is returned by [`crate::Document::begin_page()`], returned by
721 /// [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a utility
722 /// class like DebugCanvas.
723 ///
724 /// Caller must allocate pixel storage in bitmap if needed.
725 ///
726 /// [`Bitmap`] values are converted only if [`crate::ColorType`] and [`crate::AlphaType`]
727 /// do not match. Only pixels within both source and destination rectangles
728 /// are copied. [`Bitmap`] pixels outside [`Rect`] intersection are unchanged.
729 ///
730 /// Pass negative values for srcX or srcY to offset pixels across or down bitmap.
731 ///
732 /// Does not copy, and returns `false` if:
733 /// - Source and destination rectangles do not intersect.
734 /// - [`Canvas`] pixels could not be converted to `bitmap.color_type()` or
735 /// `bitmap.alpha_type()`.
736 /// - [`Canvas`] pixels are not readable; for instance, [`Canvas`] is document-based.
737 /// - bitmap pixels could not be allocated.
738 /// - `bitmap.row_bytes()` is too small to contain one row of pixels.
739 ///
740 /// - `bitmap` storage for pixels copied from [`Canvas`]
741 /// - `src` offset into readable pixels; may be negative
742 ///
743 /// Returns `true` if pixels were copied
744 ///
745 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_readPixels_3>
746 #[must_use]
747 pub fn read_pixels_to_bitmap(&self, bitmap: &mut Bitmap, src: impl Into<IPoint>) -> bool {
748 let src = src.into();
749 unsafe {
750 self.native_mut()
751 .readPixels2(bitmap.native_mut(), src.x, src.y)
752 }
753 }
754
755 /// Copies [`Rect`] from pixels to [`Canvas`]. [`Matrix`] and clip are ignored.
756 /// Source [`Rect`] corners are `(0, 0)` and `(info.width(), info.height())`.
757 /// Destination [`Rect`] corners are `(offset.x, offset.y)` and
758 /// `(image_info().width(), image_info().height())`.
759 ///
760 /// Copies each readable pixel intersecting both rectangles, without scaling,
761 /// converting to `image_info().color_type()` and `image_info().alpha_type()` if required.
762 ///
763 /// Pixels are writable when `Device` is raster, or backed by a GPU.
764 /// Pixels are not writable when [`Canvas`] is returned by [`crate::Document::begin_page()`],
765 /// returned by [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a
766 /// utility class like `DebugCanvas`.
767 ///
768 /// Pixel values are converted only if [`crate::ColorType`] and [`crate::AlphaType`]
769 /// do not match. Only pixels within both source and destination rectangles
770 /// are copied. [`Canvas`] pixels outside [`Rect`] intersection are unchanged.
771 ///
772 /// Pass negative values for `offset.x` or `offset.y` to offset pixels to the left or
773 /// above [`Canvas`] pixels.
774 ///
775 /// Does not copy, and returns `false` if:
776 /// - Source and destination rectangles do not intersect.
777 /// - pixels could not be converted to [`Canvas`] `image_info().color_type()` or
778 /// `image_info().alpha_type()`.
779 /// - [`Canvas`] pixels are not writable; for instance, [`Canvas`] is document-based.
780 /// - `row_bytes` is too small to contain one row of pixels.
781 ///
782 /// - `info` width, height, [`crate::ColorType`], and [`crate::AlphaType`] of pixels
783 /// - `pixels` pixels to copy, of size `info.height()` times `row_bytes`, or larger
784 /// - `row_bytes` size of one row of pixels; info.width() times pixel size, or larger
785 /// - `offset` offset into [`Canvas`] writable pixels; may be negative
786 ///
787 /// Returns `true` if pixels were written to [`Canvas`]
788 ///
789 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_writePixels>
790 #[must_use]
791 pub fn write_pixels(
792 &self,
793 info: &ImageInfo,
794 pixels: &[u8],
795 row_bytes: usize,
796 offset: impl Into<IPoint>,
797 ) -> bool {
798 let offset = offset.into();
799 let required_size = info.compute_byte_size(row_bytes);
800 (pixels.len() >= required_size)
801 && unsafe {
802 self.native_mut().writePixels(
803 info.native(),
804 pixels.as_ptr() as _,
805 row_bytes,
806 offset.x,
807 offset.y,
808 )
809 }
810 }
811
812 /// Copies [`Rect`] from pixels to [`Canvas`]. [`Matrix`] and clip are ignored.
813 /// Source [`Rect`] corners are `(0, 0)` and `(bitmap.width(), bitmap.height())`.
814 ///
815 /// Destination [`Rect`] corners are `(offset.x, offset.y)` and
816 /// `(image_info().width(), image_info().height())`.
817 ///
818 /// Copies each readable pixel intersecting both rectangles, without scaling,
819 /// converting to `image_info().color_type()` and `image_info().alpha_type()` if required.
820 ///
821 /// Pixels are writable when `Device` is raster, or backed by a GPU. Pixels are not writable
822 /// when [`Canvas`] is returned by [`crate::Document::begin_page()`], returned by
823 /// [`Handle<SkPictureRecorder>::begin_recording()`], or [`Canvas`] is the base of a utility
824 /// class like `DebugCanvas`.
825 ///
826 /// Pixel values are converted only if [`crate::ColorType`] and [`crate::AlphaType`]
827 /// do not match. Only pixels within both source and destination rectangles
828 /// are copied. [`Canvas`] pixels outside [`Rect`] intersection are unchanged.
829 ///
830 /// Pass negative values for `offset` to offset pixels to the left or
831 /// above [`Canvas`] pixels.
832 ///
833 /// Does not copy, and returns `false` if:
834 /// - Source and destination rectangles do not intersect.
835 /// - bitmap does not have allocated pixels.
836 /// - bitmap pixels could not be converted to [`Canvas`] `image_info().color_type()` or
837 /// `image_info().alpha_type()`.
838 /// - [`Canvas`] pixels are not writable; for instance, [`Canvas`] is document based.
839 /// - bitmap pixels are inaccessible; for instance, bitmap wraps a texture.
840 ///
841 /// - `bitmap` contains pixels copied to [`Canvas`]
842 /// - `offset` offset into [`Canvas`] writable pixels; may be negative
843 ///
844 /// Returns `true` if pixels were written to [`Canvas`]
845 ///
846 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_writePixels_2>
847 /// Example (C++): <https://fiddle.skia.org/c/@State_Stack_a>
848 /// Example (C++): <https://fiddle.skia.org/c/@State_Stack_b>
849 #[must_use]
850 pub fn write_pixels_from_bitmap(&self, bitmap: &Bitmap, offset: impl Into<IPoint>) -> bool {
851 let offset = offset.into();
852 unsafe {
853 self.native_mut()
854 .writePixels1(bitmap.native(), offset.x, offset.y)
855 }
856 }
857
858 /// Saves [`Matrix`] and clip.
859 /// Calling [`Self::restore()`] discards changes to [`Matrix`] and clip,
860 /// restoring the [`Matrix`] and clip to their state when [`Self::save()`] was called.
861 ///
862 /// [`Matrix`] may be changed by [`Self::translate()`], [`Self::scale()`], [`Self::rotate()`],
863 /// [`Self::skew()`], [`Self::concat()`], [`Self::set_matrix()`], and [`Self::reset_matrix()`].
864 /// Clip may be changed by [`Self::clip_rect()`], [`Self::clip_rrect()`], [`Self::clip_path()`],
865 /// [`Self::clip_region()`].
866 ///
867 /// Saved [`Canvas`] state is put on a stack; multiple calls to [`Self::save()`] should be
868 /// balance by an equal number of calls to [`Self::restore()`].
869 ///
870 /// Call [`Self::restore_to_count()`] with result to restore this and subsequent saves.
871 ///
872 /// Returns depth of saved stack
873 ///
874 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_save>
875 pub fn save(&self) -> usize {
876 unsafe { self.native_mut().save().try_into().unwrap() }
877 }
878
879 // The save_layer(bounds, paint) variants have been replaced by SaveLayerRec.
880
881 /// Saves [`Matrix`] and clip, and allocates [`Surface`] for subsequent drawing.
882 ///
883 /// Calling [`Self::restore()`] discards changes to [`Matrix`] and clip, and blends layer with
884 /// alpha opacity onto prior layer.
885 ///
886 /// [`Matrix`] may be changed by [`Self::translate()`], [`Self::scale()`], [`Self::rotate()`],
887 /// [`Self::skew()`], [`Self::concat()`], [`Self::set_matrix()`], and [`Self::reset_matrix()`].
888 /// Clip may be changed by [`Self::clip_rect()`], [`Self::clip_rrect()`], [`Self::clip_path()`],
889 /// [`Self::clip_region()`].
890 ///
891 /// [`Rect`] bounds suggests but does not define layer size. To clip drawing to a specific
892 /// rectangle, use [`Self::clip_rect()`].
893 ///
894 /// alpha of zero is fully transparent, 1.0 is fully opaque.
895 ///
896 /// Call [`Self::restore_to_count()`] with result to restore this and subsequent saves.
897 ///
898 /// - `bounds` hint to limit the size of layer; may be `None`
899 /// - `alpha` opacity of layer
900 ///
901 /// Returns depth of saved stack
902 ///
903 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_saveLayerAlpha>
904 pub fn save_layer_alpha_f(&self, bounds: impl Into<Option<Rect>>, alpha: f32) -> usize {
905 unsafe {
906 self.native_mut()
907 .saveLayerAlphaf(bounds.into().native().as_ptr_or_null(), alpha)
908 }
909 .try_into()
910 .unwrap()
911 }
912
913 /// Helper that accepts an int between 0 and 255, and divides it by 255.0
914 pub fn save_layer_alpha(&self, bounds: impl Into<Option<Rect>>, alpha: U8CPU) -> usize {
915 self.save_layer_alpha_f(bounds, alpha as f32 * (1.0 / 255.0))
916 }
917
918 /// Saves [`Matrix`] and clip, and allocates [`Surface`] for subsequent drawing.
919 ///
920 /// Calling [`Self::restore()`] discards changes to [`Matrix`] and clip,
921 /// and blends [`Surface`] with alpha opacity onto the prior layer.
922 ///
923 /// [`Matrix`] may be changed by [`Self::translate()`], [`Self::scale()`], [`Self::rotate()`],
924 /// [`Self::skew()`], [`Self::concat()`], [`Self::set_matrix()`], and [`Self::reset_matrix()`].
925 /// Clip may be changed by [`Self::clip_rect()`], [`Self::clip_rrect()`], [`Self::clip_path()`],
926 /// [`Self::clip_region()`].
927 ///
928 /// [`SaveLayerRec`] contains the state used to create the layer.
929 ///
930 /// Call [`Self::restore_to_count()`] with result to restore this and subsequent saves.
931 ///
932 /// - `layer_rec` layer state
933 ///
934 /// Returns depth of save state stack before this call was made.
935 ///
936 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_saveLayer>
937 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_saveLayer_4>
938 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_saveLayer_3>
939 pub fn save_layer(&self, layer_rec: &SaveLayerRec) -> usize {
940 unsafe { self.native_mut().saveLayer1(layer_rec.native()) }
941 .try_into()
942 .unwrap()
943 }
944
945 /// Removes changes to [`Matrix`] and clip since [`Canvas`] state was
946 /// last saved. The state is removed from the stack.
947 ///
948 /// Does nothing if the stack is empty.
949 ///
950 /// Example (C++): <https://fiddle.skia.org/c/@AutoCanvasRestore_restore>
951 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_restore>
952 ///
953 ///
954 pub fn restore(&self) -> &Self {
955 unsafe { self.native_mut().restore() };
956 self
957 }
958
959 /// Returns the number of saved states, each containing: [`Matrix`] and clip.
960 /// Equals the number of [`Self::save()`] calls less the number of [`Self::restore()`] calls
961 /// plus one.
962 /// The save count of a new canvas is one.
963 ///
964 /// Returns depth of save state stack
965 ///
966 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_getSaveCount>
967 pub fn save_count(&self) -> usize {
968 unsafe { self.native().getSaveCount() }.try_into().unwrap()
969 }
970
971 /// Restores state to [`Matrix`] and clip values when [`Self::save()`], [`Self::save_layer()`],
972 /// or [`Self::save_layer_alpha()`] returned `save_count`.
973 ///
974 /// Does nothing if `save_count` is greater than state stack count.
975 /// Restores state to initial values if `save_count` is less than or equal to one.
976 ///
977 /// - `saveCount` depth of state stack to restore
978 ///
979 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_restoreToCount>
980 pub fn restore_to_count(&self, save_count: usize) -> &Self {
981 unsafe {
982 self.native_mut()
983 .restoreToCount(save_count.try_into().unwrap())
984 }
985 self
986 }
987
988 /// Translates [`Matrix`] by `d`.
989 ///
990 /// Mathematically, replaces [`Matrix`] with a translation matrix premultiplied with [`Matrix`].
991 ///
992 /// This has the effect of moving the drawing by `(d.x, d.y)` before transforming the result
993 /// with [`Matrix`].
994 ///
995 /// - `d` distance to translate
996 ///
997 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_translate>
998 pub fn translate(&self, d: impl Into<Vector>) -> &Self {
999 let d = d.into();
1000 unsafe { self.native_mut().translate(d.x, d.y) }
1001 self
1002 }
1003
1004 /// Scales [`Matrix`] by `sx` on the x-axis and `sy` on the y-axis.
1005 ///
1006 /// Mathematically, replaces [`Matrix`] with a scale matrix premultiplied with [`Matrix`].
1007 ///
1008 /// This has the effect of scaling the drawing by `(sx, sy)` before transforming the result with
1009 /// [`Matrix`].
1010 ///
1011 /// - `sx` amount to scale on x-axis
1012 /// - `sy` amount to scale on y-axis
1013 ///
1014 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_scale>
1015 pub fn scale(&self, (sx, sy): (scalar, scalar)) -> &Self {
1016 unsafe { self.native_mut().scale(sx, sy) }
1017 self
1018 }
1019
1020 /// Rotates [`Matrix`] by degrees about a point at `(p.x, p.y)`. Positive degrees rotates
1021 /// clockwise.
1022 ///
1023 /// Mathematically, constructs a rotation matrix; premultiplies the rotation matrix by a
1024 /// translation matrix; then replaces [`Matrix`] with the resulting matrix premultiplied with
1025 /// [`Matrix`].
1026 ///
1027 /// This has the effect of rotating the drawing about a given point before transforming the
1028 /// result with [`Matrix`].
1029 ///
1030 /// - `degrees` amount to rotate, in degrees
1031 /// - `p` the point to rotate about
1032 ///
1033 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_rotate>
1034 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_rotate_2>
1035 pub fn rotate(&self, degrees: scalar, p: Option<Point>) -> &Self {
1036 unsafe {
1037 match p {
1038 Some(point) => self.native_mut().rotate1(degrees, point.x, point.y),
1039 None => self.native_mut().rotate(degrees),
1040 }
1041 }
1042 self
1043 }
1044
1045 /// Skews [`Matrix`] by `sx` on the x-axis and `sy` on the y-axis. A positive value of `sx`
1046 /// skews the drawing right as y-axis values increase; a positive value of `sy` skews the
1047 /// drawing down as x-axis values increase.
1048 ///
1049 /// Mathematically, replaces [`Matrix`] with a skew matrix premultiplied with [`Matrix`].
1050 ///
1051 /// This has the effect of skewing the drawing by `(sx, sy)` before transforming the result with
1052 /// [`Matrix`].
1053 ///
1054 /// - `sx` amount to skew on x-axis
1055 /// - `sy` amount to skew on y-axis
1056 ///
1057 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_skew>
1058 pub fn skew(&self, (sx, sy): (scalar, scalar)) -> &Self {
1059 unsafe { self.native_mut().skew(sx, sy) }
1060 self
1061 }
1062
1063 /// Replaces [`Matrix`] with matrix premultiplied with existing [`Matrix`].
1064 ///
1065 /// This has the effect of transforming the drawn geometry by matrix, before transforming the
1066 /// result with existing [`Matrix`].
1067 ///
1068 /// - `matrix` matrix to premultiply with existing [`Matrix`]
1069 ///
1070 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_concat>
1071 pub fn concat(&self, matrix: &Matrix) -> &Self {
1072 unsafe { self.native_mut().concat(matrix.native()) }
1073 self
1074 }
1075
1076 pub fn concat_44(&self, m: &M44) -> &Self {
1077 unsafe { self.native_mut().concat1(m.native()) }
1078 self
1079 }
1080
1081 /// Replaces [`Matrix`] with `matrix`.
1082 /// Unlike [`Self::concat()`], any prior matrix state is overwritten.
1083 ///
1084 /// - `matrix` matrix to copy, replacing existing [`Matrix`]
1085 ///
1086 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_setMatrix>
1087 pub fn set_matrix(&self, matrix: &M44) -> &Self {
1088 unsafe { self.native_mut().setMatrix(matrix.native()) }
1089 self
1090 }
1091
1092 /// Sets [`Matrix`] to the identity matrix.
1093 /// Any prior matrix state is overwritten.
1094 ///
1095 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_resetMatrix>
1096 pub fn reset_matrix(&self) -> &Self {
1097 unsafe { self.native_mut().resetMatrix() }
1098 self
1099 }
1100
1101 /// Replaces clip with the intersection or difference of clip and `rect`,
1102 /// with an aliased or anti-aliased clip edge. `rect` is transformed by [`Matrix`]
1103 /// before it is combined with clip.
1104 ///
1105 /// - `rect` [`Rect`] to combine with clip
1106 /// - `op` [`ClipOp`] to apply to clip
1107 /// - `do_anti_alias` `true` if clip is to be anti-aliased
1108 ///
1109 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_clipRect>
1110 pub fn clip_rect(
1111 &self,
1112 rect: impl AsRef<Rect>,
1113 op: impl Into<Option<ClipOp>>,
1114 do_anti_alias: impl Into<Option<bool>>,
1115 ) -> &Self {
1116 unsafe {
1117 self.native_mut().clipRect(
1118 rect.as_ref().native(),
1119 op.into().unwrap_or_default(),
1120 do_anti_alias.into().unwrap_or_default(),
1121 )
1122 }
1123 self
1124 }
1125
1126 pub fn clip_irect(&self, irect: impl AsRef<IRect>, op: impl Into<Option<ClipOp>>) -> &Self {
1127 let r = Rect::from(*irect.as_ref());
1128 self.clip_rect(r, op, false)
1129 }
1130
1131 /// Replaces clip with the intersection or difference of clip and `rrect`,
1132 /// with an aliased or anti-aliased clip edge.
1133 /// `rrect` is transformed by [`Matrix`]
1134 /// before it is combined with clip.
1135 ///
1136 /// - `rrect` [`RRect`] to combine with clip
1137 /// - `op` [`ClipOp`] to apply to clip
1138 /// - `do_anti_alias` `true` if clip is to be anti-aliased
1139 ///
1140 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_clipRRect>
1141 pub fn clip_rrect(
1142 &self,
1143 rrect: impl AsRef<RRect>,
1144 op: impl Into<Option<ClipOp>>,
1145 do_anti_alias: impl Into<Option<bool>>,
1146 ) -> &Self {
1147 unsafe {
1148 self.native_mut().clipRRect(
1149 rrect.as_ref().native(),
1150 op.into().unwrap_or_default(),
1151 do_anti_alias.into().unwrap_or_default(),
1152 )
1153 }
1154 self
1155 }
1156
1157 /// Replaces clip with the intersection or difference of clip and `path`,
1158 /// with an aliased or anti-aliased clip edge. [`crate::PathFillType`] determines if `path`
1159 /// describes the area inside or outside its contours; and if path contour overlaps
1160 /// itself or another path contour, whether the overlaps form part of the area.
1161 /// `path` is transformed by [`Matrix`] before it is combined with clip.
1162 ///
1163 /// - `path` [`Path`] to combine with clip
1164 /// - `op` [`ClipOp`] to apply to clip
1165 /// - `do_anti_alias` `true` if clip is to be anti-aliased
1166 ///
1167 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_clipPath>
1168 pub fn clip_path(
1169 &self,
1170 path: &Path,
1171 op: impl Into<Option<ClipOp>>,
1172 do_anti_alias: impl Into<Option<bool>>,
1173 ) -> &Self {
1174 unsafe {
1175 self.native_mut().clipPath(
1176 path.native(),
1177 op.into().unwrap_or_default(),
1178 do_anti_alias.into().unwrap_or_default(),
1179 )
1180 }
1181 self
1182 }
1183
1184 pub fn clip_shader(&self, shader: impl Into<Shader>, op: impl Into<Option<ClipOp>>) -> &Self {
1185 unsafe {
1186 sb::C_SkCanvas_clipShader(
1187 self.native_mut(),
1188 shader.into().into_ptr(),
1189 op.into().unwrap_or(ClipOp::Intersect),
1190 )
1191 }
1192 self
1193 }
1194
1195 /// Replaces clip with the intersection or difference of clip and [`Region`] `device_rgn`.
1196 /// Resulting clip is aliased; pixels are fully contained by the clip.
1197 /// `device_rgn` is unaffected by [`Matrix`].
1198 ///
1199 /// - `device_rgn` [`Region`] to combine with clip
1200 /// - `op` [`ClipOp`] to apply to clip
1201 ///
1202 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_clipRegion>
1203 pub fn clip_region(&self, device_rgn: &Region, op: impl Into<Option<ClipOp>>) -> &Self {
1204 unsafe {
1205 self.native_mut()
1206 .clipRegion(device_rgn.native(), op.into().unwrap_or_default())
1207 }
1208 self
1209 }
1210
1211 // quickReject() functions are implemented as a trait.
1212
1213 /// Returns bounds of clip, transformed by inverse of [`Matrix`]. If clip is empty,
1214 /// return [`Rect::new_empty()`], where all [`Rect`] sides equal zero.
1215 ///
1216 /// [`Rect`] returned is outset by one to account for partial pixel coverage if clip
1217 /// is anti-aliased.
1218 ///
1219 /// Returns bounds of clip in local coordinates
1220 ///
1221 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_getLocalClipBounds>
1222 pub fn local_clip_bounds(&self) -> Option<Rect> {
1223 let r = Rect::construct(|r| unsafe { sb::C_SkCanvas_getLocalClipBounds(self.native(), r) });
1224 (!r.is_empty()).then_some(r)
1225 }
1226
1227 /// Returns [`IRect`] bounds of clip, unaffected by [`Matrix`]. If clip is empty,
1228 /// return [`Rect::new_empty()`], where all [`Rect`] sides equal zero.
1229 ///
1230 /// Unlike [`Self::local_clip_bounds()`], returned [`IRect`] is not outset.
1231 ///
1232 /// Returns bounds of clip in `Device` coordinates
1233 ///
1234 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_getDeviceClipBounds>
1235 pub fn device_clip_bounds(&self) -> Option<IRect> {
1236 let r =
1237 IRect::construct(|r| unsafe { sb::C_SkCanvas_getDeviceClipBounds(self.native(), r) });
1238 (!r.is_empty()).then_some(r)
1239 }
1240
1241 /// Fills clip with color `color`.
1242 /// `mode` determines how ARGB is combined with destination.
1243 ///
1244 /// - `color` [`Color4f`] representing unpremultiplied color.
1245 /// - `mode` [`BlendMode`] used to combine source color and destination
1246 ///
1247 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawColor>
1248 pub fn draw_color(
1249 &self,
1250 color: impl Into<Color4f>,
1251 mode: impl Into<Option<BlendMode>>,
1252 ) -> &Self {
1253 unsafe {
1254 self.native_mut()
1255 .drawColor(&color.into().into_native(), mode.into().unwrap_or_default())
1256 }
1257 self
1258 }
1259
1260 /// Fills clip with color `color` using [`BlendMode::Src`].
1261 /// This has the effect of replacing all pixels contained by clip with `color`.
1262 ///
1263 /// - `color` [`Color4f`] representing unpremultiplied color.
1264 pub fn clear(&self, color: impl Into<Color4f>) -> &Self {
1265 self.draw_color(color, BlendMode::Src)
1266 }
1267
1268 /// Makes [`Canvas`] contents undefined. Subsequent calls that read [`Canvas`] pixels,
1269 /// such as drawing with [`BlendMode`], return undefined results. `discard()` does
1270 /// not change clip or [`Matrix`].
1271 ///
1272 /// `discard()` may do nothing, depending on the implementation of [`Surface`] or `Device`
1273 /// that created [`Canvas`].
1274 ///
1275 /// `discard()` allows optimized performance on subsequent draws by removing
1276 /// cached data associated with [`Surface`] or `Device`.
1277 /// It is not necessary to call `discard()` once done with [`Canvas`];
1278 /// any cached data is deleted when owning [`Surface`] or `Device` is deleted.
1279 pub fn discard(&self) -> &Self {
1280 unsafe { sb::C_SkCanvas_discard(self.native_mut()) }
1281 self
1282 }
1283
1284 /// Fills clip with [`Paint`] `paint`. [`Paint`] components, [`Shader`],
1285 /// [`crate::ColorFilter`], [`ImageFilter`], and [`BlendMode`] affect drawing;
1286 /// [`crate::MaskFilter`] and [`crate::PathEffect`] in `paint` are ignored.
1287 ///
1288 /// - `paint` graphics state used to fill [`Canvas`]
1289 ///
1290 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawPaint>
1291 pub fn draw_paint(&self, paint: &Paint) -> &Self {
1292 unsafe { self.native_mut().drawPaint(paint.native()) }
1293 self
1294 }
1295
1296 /// Draws `pts` using clip, [`Matrix`] and [`Paint`] `pain`.
1297 /// if the number of points is less than one, has no effect.
1298 /// `mode` may be one of: [`PointMode::Points`], [`PointMode::Lines`], or [`PointMode::Polygon`]
1299 ///
1300 /// If `mode` is [`PointMode::Points`], the shape of point drawn depends on `paint`
1301 /// [`crate::paint::Cap`]. If `paint` is set to [`crate::paint::Cap::Round`], each point draws a
1302 /// circle of diameter [`Paint`] stroke width. If `paint` is set to [`crate::paint::Cap::Square`]
1303 /// or [`crate::paint::Cap::Butt`], each point draws a square of width and height
1304 /// [`Paint`] stroke width.
1305 ///
1306 /// If `mode` is [`PointMode::Lines`], each pair of points draws a line segment.
1307 /// One line is drawn for every two points; each point is used once. If count is odd,
1308 /// the final point is ignored.
1309 ///
1310 /// If mode is [`PointMode::Polygon`], each adjacent pair of points draws a line segment.
1311 /// count minus one lines are drawn; the first and last point are used once.
1312 ///
1313 /// Each line segment respects `paint` [`crate::paint::Cap`] and [`Paint`] stroke width.
1314 /// [`crate::paint::Style`] is ignored, as if were set to [`crate::paint::Style::Stroke`].
1315 ///
1316 /// Always draws each element one at a time; is not affected by
1317 /// [`crate::paint::Join`], and unlike [`Self::draw_path()`], does not create a mask from all points
1318 /// and lines before drawing.
1319 ///
1320 /// - `mode` whether pts draws points or lines
1321 /// - `pts` array of points to draw
1322 /// - `paint` stroke, blend, color, and so on, used to draw
1323 ///
1324 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawPoints>
1325 pub fn draw_points(&self, mode: PointMode, pts: &[Point], paint: &Paint) -> &Self {
1326 unsafe {
1327 sb::C_SkCanvas_drawPoints(
1328 self.native_mut(),
1329 mode,
1330 pts.native().as_ptr(),
1331 pts.len(),
1332 paint.native(),
1333 )
1334 }
1335 self
1336 }
1337
1338 /// Draws point `p` using clip, [`Matrix`] and [`Paint`] paint.
1339 ///
1340 /// The shape of point drawn depends on `paint` [`crate::paint::Cap`].
1341 /// If `paint` is set to [`crate::paint::Cap::Round`], draw a circle of diameter [`Paint`]
1342 /// stroke width. If `paint` is set to [`crate::paint::Cap::Square`] or
1343 /// [`crate::paint::Cap::Butt`], draw a square of width and height [`Paint`] stroke width.
1344 /// [`crate::paint::Style`] is ignored, as if were set to [`crate::paint::Style::Stroke`].
1345 ///
1346 /// - `p` top-left edge of circle or square
1347 /// - `paint` stroke, blend, color, and so on, used to draw
1348 ///
1349 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawPoint>
1350 pub fn draw_point(&self, p: impl Into<Point>, paint: &Paint) -> &Self {
1351 let p = p.into();
1352 unsafe { self.native_mut().drawPoint(p.x, p.y, paint.native()) }
1353 self
1354 }
1355
1356 /// Draws line segment from `p1` to `p2` using clip, [`Matrix`], and [`Paint`] paint.
1357 /// In paint: [`Paint`] stroke width describes the line thickness;
1358 /// [`crate::paint::Cap`] draws the end rounded or square;
1359 /// [`crate::paint::Style`] is ignored, as if were set to [`crate::paint::Style::Stroke`].
1360 ///
1361 /// - `p1` start of line segment
1362 /// - `p2` end of line segment
1363 /// - `paint` stroke, blend, color, and so on, used to draw
1364 ///
1365 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawLine>
1366 pub fn draw_line(&self, p1: impl Into<Point>, p2: impl Into<Point>, paint: &Paint) -> &Self {
1367 let (p1, p2) = (p1.into(), p2.into());
1368 unsafe {
1369 self.native_mut()
1370 .drawLine(p1.x, p1.y, p2.x, p2.y, paint.native())
1371 }
1372 self
1373 }
1374
1375 /// Draws [`Rect`] rect using clip, [`Matrix`], and [`Paint`] `paint`.
1376 /// In paint: [`crate::paint::Style`] determines if rectangle is stroked or filled;
1377 /// if stroked, [`Paint`] stroke width describes the line thickness, and
1378 /// [`crate::paint::Join`] draws the corners rounded or square.
1379 ///
1380 /// - `rect` rectangle to draw
1381 /// - `paint` stroke or fill, blend, color, and so on, used to draw
1382 ///
1383 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawRect>
1384 pub fn draw_rect(&self, rect: impl AsRef<Rect>, paint: &Paint) -> &Self {
1385 unsafe {
1386 self.native_mut()
1387 .drawRect(rect.as_ref().native(), paint.native())
1388 }
1389 self
1390 }
1391
1392 /// Draws [`IRect`] rect using clip, [`Matrix`], and [`Paint`] `paint`.
1393 /// In `paint`: [`crate::paint::Style`] determines if rectangle is stroked or filled;
1394 /// if stroked, [`Paint`] stroke width describes the line thickness, and
1395 /// [`crate::paint::Join`] draws the corners rounded or square.
1396 ///
1397 /// - `rect` rectangle to draw
1398 /// - `paint` stroke or fill, blend, color, and so on, used to draw
1399 pub fn draw_irect(&self, rect: impl AsRef<IRect>, paint: &Paint) -> &Self {
1400 self.draw_rect(Rect::from(*rect.as_ref()), paint)
1401 }
1402
1403 /// Draws [`Region`] region using clip, [`Matrix`], and [`Paint`] `paint`.
1404 /// In `paint`: [`crate::paint::Style`] determines if rectangle is stroked or filled;
1405 /// if stroked, [`Paint`] stroke width describes the line thickness, and
1406 /// [`crate::paint::Join`] draws the corners rounded or square.
1407 ///
1408 /// - `region` region to draw
1409 /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1410 ///
1411 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawRegion>
1412 pub fn draw_region(&self, region: &Region, paint: &Paint) -> &Self {
1413 unsafe {
1414 self.native_mut()
1415 .drawRegion(region.native(), paint.native())
1416 }
1417 self
1418 }
1419
1420 /// Draws oval oval using clip, [`Matrix`], and [`Paint`].
1421 /// In `paint`: [`crate::paint::Style`] determines if oval is stroked or filled;
1422 /// if stroked, [`Paint`] stroke width describes the line thickness.
1423 ///
1424 /// - `oval` [`Rect`] bounds of oval
1425 /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1426 ///
1427 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawOval>
1428 pub fn draw_oval(&self, oval: impl AsRef<Rect>, paint: &Paint) -> &Self {
1429 unsafe {
1430 self.native_mut()
1431 .drawOval(oval.as_ref().native(), paint.native())
1432 }
1433 self
1434 }
1435
1436 /// Draws [`RRect`] rrect using clip, [`Matrix`], and [`Paint`] `paint`.
1437 /// In `paint`: [`crate::paint::Style`] determines if rrect is stroked or filled;
1438 /// if stroked, [`Paint`] stroke width describes the line thickness.
1439 ///
1440 /// `rrect` may represent a rectangle, circle, oval, uniformly rounded rectangle, or
1441 /// may have any combination of positive non-square radii for the four corners.
1442 ///
1443 /// - `rrect` [`RRect`] with up to eight corner radii to draw
1444 /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1445 ///
1446 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawRRect>
1447 pub fn draw_rrect(&self, rrect: impl AsRef<RRect>, paint: &Paint) -> &Self {
1448 unsafe {
1449 self.native_mut()
1450 .drawRRect(rrect.as_ref().native(), paint.native())
1451 }
1452 self
1453 }
1454
1455 /// Draws [`RRect`] outer and inner
1456 /// using clip, [`Matrix`], and [`Paint`] `paint`.
1457 /// outer must contain inner or the drawing is undefined.
1458 /// In paint: [`crate::paint::Style`] determines if [`RRect`] is stroked or filled;
1459 /// if stroked, [`Paint`] stroke width describes the line thickness.
1460 /// If stroked and [`RRect`] corner has zero length radii, [`crate::paint::Join`] can
1461 /// draw corners rounded or square.
1462 ///
1463 /// GPU-backed platforms optimize drawing when both outer and inner are
1464 /// concave and outer contains inner. These platforms may not be able to draw
1465 /// [`Path`] built with identical data as fast.
1466 ///
1467 /// - `outer` [`RRect`] outer bounds to draw
1468 /// - `inner` [`RRect`] inner bounds to draw
1469 /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1470 ///
1471 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawDRRect_a>
1472 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawDRRect_b>
1473 pub fn draw_drrect(
1474 &self,
1475 outer: impl AsRef<RRect>,
1476 inner: impl AsRef<RRect>,
1477 paint: &Paint,
1478 ) -> &Self {
1479 unsafe {
1480 self.native_mut().drawDRRect(
1481 outer.as_ref().native(),
1482 inner.as_ref().native(),
1483 paint.native(),
1484 )
1485 }
1486 self
1487 }
1488
1489 /// Draws circle at center with radius using clip, [`Matrix`], and [`Paint`] `paint`.
1490 /// If radius is zero or less, nothing is drawn.
1491 /// In `paint`: [`crate::paint::Style`] determines if circle is stroked or filled;
1492 /// if stroked, [`Paint`] stroke width describes the line thickness.
1493 ///
1494 /// - `center` circle center
1495 /// - `radius` half the diameter of circle
1496 /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1497 ///
1498 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawCircle>
1499 pub fn draw_circle(&self, center: impl Into<Point>, radius: scalar, paint: &Paint) -> &Self {
1500 let center = center.into();
1501 unsafe {
1502 self.native_mut()
1503 .drawCircle(center.x, center.y, radius, paint.native())
1504 }
1505 self
1506 }
1507
1508 /// Draws arc using clip, [`Matrix`], and [`Paint`] paint.
1509 ///
1510 /// Arc is part of oval bounded by oval, sweeping from `start_angle` to `start_angle` plus
1511 /// `sweep_angle`. `start_angle` and `sweep_angle` are in degrees.
1512 ///
1513 /// `start_angle` of zero places start point at the right middle edge of oval.
1514 /// A positive `sweep_angle` places arc end point clockwise from start point;
1515 /// a negative `sweep_angle` places arc end point counterclockwise from start point.
1516 /// `sweep_angle` may exceed 360 degrees, a full circle.
1517 /// If `use_center` is `true`, draw a wedge that includes lines from oval
1518 /// center to arc end points. If `use_center` is `false`, draw arc between end points.
1519 ///
1520 /// If [`Rect`] oval is empty or `sweep_angle` is zero, nothing is drawn.
1521 ///
1522 /// - `oval` [`Rect`] bounds of oval containing arc to draw
1523 /// - `start_angle` angle in degrees where arc begins
1524 /// - `sweep_angle` sweep angle in degrees; positive is clockwise
1525 /// - `use_center` if `true`, include the center of the oval
1526 /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1527 pub fn draw_arc(
1528 &self,
1529 oval: impl AsRef<Rect>,
1530 start_angle: scalar,
1531 sweep_angle: scalar,
1532 use_center: bool,
1533 paint: &Paint,
1534 ) -> &Self {
1535 unsafe {
1536 self.native_mut().drawArc(
1537 oval.as_ref().native(),
1538 start_angle,
1539 sweep_angle,
1540 use_center,
1541 paint.native(),
1542 )
1543 }
1544 self
1545 }
1546
1547 /// Draws arc using clip, [`Matrix`], and [`Paint`] paint.
1548 ///
1549 /// Arc is part of oval bounded by oval, sweeping from `start_angle` to `start_angle` plus
1550 /// `sweep_angle`. `start_angle` and `sweep_angle` are in degrees.
1551 ///
1552 /// `start_angle` of zero places start point at the right middle edge of oval.
1553 /// A positive `sweep_angle` places arc end point clockwise from start point;
1554 /// a negative `sweep_angle` places arc end point counterclockwise from start point.
1555 /// `sweep_angle` may exceed 360 degrees, a full circle.
1556 /// If `use_center` is `true`, draw a wedge that includes lines from oval
1557 /// center to arc end points. If `use_center` is `false`, draw arc between end points.
1558 ///
1559 /// If [`Rect`] oval is empty or `sweep_angle` is zero, nothing is drawn.
1560 ///
1561 /// - `arc` [`Arc`] specifying oval, startAngle, sweepAngle, and arc-vs-wedge
1562 /// - `paint` [`Paint`] stroke or fill, blend, color, and so on, used to draw
1563 pub fn draw_arc_2(&self, arc: &Arc, paint: &Paint) -> &Self {
1564 self.draw_arc(
1565 arc.oval,
1566 arc.start_angle,
1567 arc.sweep_angle,
1568 arc.is_wedge(),
1569 paint,
1570 );
1571 self
1572 }
1573
1574 /// Draws [`RRect`] bounded by [`Rect`] rect, with corner radii `(rx, ry)` using clip,
1575 /// [`Matrix`], and [`Paint`] `paint`.
1576 ///
1577 /// In `paint`: [`crate::paint::Style`] determines if [`RRect`] is stroked or filled;
1578 /// if stroked, [`Paint`] stroke width describes the line thickness.
1579 /// If `rx` or `ry` are less than zero, they are treated as if they are zero.
1580 /// If `rx` plus `ry` exceeds rect width or rect height, radii are scaled down to fit.
1581 /// If `rx` and `ry` are zero, [`RRect`] is drawn as [`Rect`] and if stroked is affected by
1582 /// [`crate::paint::Join`].
1583 ///
1584 /// - `rect` [`Rect`] bounds of [`RRect`] to draw
1585 /// - `rx` axis length on x-axis of oval describing rounded corners
1586 /// - `ry` axis length on y-axis of oval describing rounded corners
1587 /// - `paint` stroke, blend, color, and so on, used to draw
1588 ///
1589 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawRoundRect>
1590 pub fn draw_round_rect(
1591 &self,
1592 rect: impl AsRef<Rect>,
1593 rx: scalar,
1594 ry: scalar,
1595 paint: &Paint,
1596 ) -> &Self {
1597 unsafe {
1598 self.native_mut()
1599 .drawRoundRect(rect.as_ref().native(), rx, ry, paint.native())
1600 }
1601 self
1602 }
1603
1604 /// Draws [`Path`] path using clip, [`Matrix`], and [`Paint`] `paint`.
1605 /// [`Path`] contains an array of path contour, each of which may be open or closed.
1606 ///
1607 /// In `paint`: [`crate::paint::Style`] determines if [`RRect`] is stroked or filled:
1608 /// if filled, [`crate::PathFillType`] determines whether path contour describes inside or
1609 /// outside of fill; if stroked, [`Paint`] stroke width describes the line thickness,
1610 /// [`crate::paint::Cap`] describes line ends, and [`crate::paint::Join`] describes how
1611 /// corners are drawn.
1612 ///
1613 /// - `path` [`Path`] to draw
1614 /// - `paint` stroke, blend, color, and so on, used to draw
1615 ///
1616 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawPath>
1617 pub fn draw_path(&self, path: &Path, paint: &Paint) -> &Self {
1618 unsafe { self.native_mut().drawPath(path.native(), paint.native()) }
1619 self
1620 }
1621
1622 pub fn draw_image(
1623 &self,
1624 image: impl AsRef<Image>,
1625 left_top: impl Into<Point>,
1626 paint: Option<&Paint>,
1627 ) -> &Self {
1628 let left_top = left_top.into();
1629 self.draw_image_with_sampling_options(image, left_top, SamplingOptions::default(), paint)
1630 }
1631
1632 pub fn draw_image_rect(
1633 &self,
1634 image: impl AsRef<Image>,
1635 src: Option<(&Rect, SrcRectConstraint)>,
1636 dst: impl AsRef<Rect>,
1637 paint: &Paint,
1638 ) -> &Self {
1639 self.draw_image_rect_with_sampling_options(
1640 image,
1641 src,
1642 dst,
1643 SamplingOptions::default(),
1644 paint,
1645 )
1646 }
1647
1648 pub fn draw_image_with_sampling_options(
1649 &self,
1650 image: impl AsRef<Image>,
1651 left_top: impl Into<Point>,
1652 sampling: impl Into<SamplingOptions>,
1653 paint: Option<&Paint>,
1654 ) -> &Self {
1655 let left_top = left_top.into();
1656 unsafe {
1657 self.native_mut().drawImage(
1658 image.as_ref().native(),
1659 left_top.x,
1660 left_top.y,
1661 sampling.into().native(),
1662 paint.native_ptr_or_null(),
1663 )
1664 }
1665 self
1666 }
1667
1668 pub fn draw_image_rect_with_sampling_options(
1669 &self,
1670 image: impl AsRef<Image>,
1671 src: Option<(&Rect, SrcRectConstraint)>,
1672 dst: impl AsRef<Rect>,
1673 sampling: impl Into<SamplingOptions>,
1674 paint: &Paint,
1675 ) -> &Self {
1676 let sampling = sampling.into();
1677 match src {
1678 Some((src, constraint)) => unsafe {
1679 self.native_mut().drawImageRect(
1680 image.as_ref().native(),
1681 src.native(),
1682 dst.as_ref().native(),
1683 sampling.native(),
1684 paint.native(),
1685 constraint,
1686 )
1687 },
1688 None => unsafe {
1689 self.native_mut().drawImageRect1(
1690 image.as_ref().native(),
1691 dst.as_ref().native(),
1692 sampling.native(),
1693 paint.native(),
1694 )
1695 },
1696 }
1697 self
1698 }
1699
1700 /// Draws [`Image`] `image` stretched proportionally to fit into [`Rect`] `dst`.
1701 /// [`IRect`] `center` divides the image into nine sections: four sides, four corners, and
1702 /// the center. Corners are unmodified or scaled down proportionately if their sides
1703 /// are larger than `dst`; center and four sides are scaled to fit remaining space, if any.
1704 ///
1705 /// Additionally transform draw using clip, [`Matrix`], and optional [`Paint`] `paint`.
1706 ///
1707 /// If [`Paint`] `paint` is supplied, apply [`crate::ColorFilter`], alpha, [`ImageFilter`], and
1708 /// [`BlendMode`]. If `image` is [`crate::ColorType::Alpha8`], apply [`Shader`].
1709 /// If `paint` contains [`crate::MaskFilter`], generate mask from `image` bounds.
1710 /// Any [`crate::MaskFilter`] on `paint` is ignored as is paint anti-aliasing state.
1711 ///
1712 /// If generated mask extends beyond image bounds, replicate image edge colors, just
1713 /// as [`Shader`] made from [`RCHandle<Image>::to_shader()`] with [`crate::TileMode::Clamp`] set
1714 /// replicates the image edge color when it samples outside of its bounds.
1715 ///
1716 /// - `image` [`Image`] containing pixels, dimensions, and format
1717 /// - `center` [`IRect`] edge of image corners and sides
1718 /// - `dst` destination [`Rect`] of image to draw to
1719 /// - `filter` what technique to use when sampling the image
1720 /// - `paint` [`Paint`] containing [`BlendMode`], [`crate::ColorFilter`], [`ImageFilter`],
1721 /// and so on; or `None`
1722 pub fn draw_image_nine(
1723 &self,
1724 image: impl AsRef<Image>,
1725 center: impl AsRef<IRect>,
1726 dst: impl AsRef<Rect>,
1727 filter_mode: FilterMode,
1728 paint: Option<&Paint>,
1729 ) -> &Self {
1730 unsafe {
1731 self.native_mut().drawImageNine(
1732 image.as_ref().native(),
1733 center.as_ref().native(),
1734 dst.as_ref().native(),
1735 filter_mode,
1736 paint.native_ptr_or_null(),
1737 )
1738 }
1739 self
1740 }
1741
1742 /// Draws [`Image`] `image` stretched proportionally to fit into [`Rect`] `dst`.
1743 ///
1744 /// [`lattice::Lattice`] lattice divides image into a rectangular grid.
1745 /// Each intersection of an even-numbered row and column is fixed;
1746 /// fixed lattice elements never scale larger than their initial
1747 /// size and shrink proportionately when all fixed elements exceed the bitmap
1748 /// dimension. All other grid elements scale to fill the available space, if any.
1749 ///
1750 /// Additionally transform draw using clip, [`Matrix`], and optional [`Paint`] `paint`.
1751 ///
1752 /// If [`Paint`] `paint` is supplied, apply [`crate::ColorFilter`], alpha, [`ImageFilter`], and
1753 /// [`BlendMode`]. If image is [`crate::ColorType::Alpha8`], apply [`Shader`].
1754 /// If `paint` contains [`crate::MaskFilter`], generate mask from image bounds.
1755 /// Any [`crate::MaskFilter`] on `paint` is ignored as is `paint` anti-aliasing state.
1756 ///
1757 /// If generated mask extends beyond bitmap bounds, replicate bitmap edge colors,
1758 /// just as [`Shader`] made from `SkShader::MakeBitmapShader` with
1759 /// [`crate::TileMode::Clamp`] set replicates the bitmap edge color when it samples
1760 /// outside of its bounds.
1761 ///
1762 /// - `image` [`Image`] containing pixels, dimensions, and format
1763 /// - `lattice` division of bitmap into fixed and variable rectangles
1764 /// - `dst` destination [`Rect`] of image to draw to
1765 /// - `filter` what technique to use when sampling the image
1766 /// - `paint` [`Paint`] containing [`BlendMode`], [`crate::ColorFilter`], [`ImageFilter`],
1767 /// and so on; or `None`
1768 pub fn draw_image_lattice(
1769 &self,
1770 image: impl AsRef<Image>,
1771 lattice: &Lattice,
1772 dst: impl AsRef<Rect>,
1773 filter: FilterMode,
1774 paint: Option<&Paint>,
1775 ) -> &Self {
1776 unsafe {
1777 self.native_mut().drawImageLattice(
1778 image.as_ref().native(),
1779 &lattice.native().native,
1780 dst.as_ref().native(),
1781 filter,
1782 paint.native_ptr_or_null(),
1783 )
1784 }
1785 self
1786 }
1787
1788 // TODO: drawSimpleText?
1789
1790 /// Draws [`String`], with origin at `(origin.x, origin.y)`, using clip, [`Matrix`], [`Font`]
1791 /// `font`, and [`Paint`] `paint`.
1792 ///
1793 /// This function uses the default character-to-glyph mapping from the [`crate::Typeface`] in
1794 /// font. It does not perform typeface fallback for characters not found in the
1795 /// [`crate::Typeface`]. It does not perform kerning; glyphs are positioned based on their
1796 /// default advances.
1797 ///
1798 /// Text size is affected by [`Matrix`] and [`Font`] text size. Default text size is 12 point.
1799 ///
1800 /// All elements of `paint`: [`crate::PathEffect`], [`crate::MaskFilter`], [`Shader`],
1801 /// [`crate::ColorFilter`], and [`ImageFilter`]; apply to text. By default, draws filled black
1802 /// glyphs.
1803 ///
1804 /// - `str` character code points drawn,
1805 /// ending with a char value of zero
1806 /// - `origin` start of string on x,y-axis
1807 /// - `font` typeface, text size and so, used to describe the text
1808 /// - `paint` blend, color, and so on, used to draw
1809 pub fn draw_str(
1810 &self,
1811 str: impl AsRef<str>,
1812 origin: impl Into<Point>,
1813 font: &Font,
1814 paint: &Paint,
1815 ) -> &Self {
1816 // rust specific, based on drawSimpleText with fixed UTF8 encoding,
1817 // implementation is similar to Font's *_str methods.
1818 let origin = origin.into();
1819 let bytes = str.as_ref().as_bytes();
1820 unsafe {
1821 self.native_mut().drawSimpleText(
1822 bytes.as_ptr() as _,
1823 bytes.len(),
1824 TextEncoding::UTF8.into_native(),
1825 origin.x,
1826 origin.y,
1827 font.native(),
1828 paint.native(),
1829 )
1830 }
1831 self
1832 }
1833
1834 /// Draws glyphs at positions relative to `origin` styled with `font` and `paint` with
1835 /// supporting utf8 and cluster information.
1836 ///
1837 /// This function draw glyphs at the given positions relative to the given origin. It does not
1838 /// perform typeface fallback for glyphs not found in the [`crate::Typeface`] in font.
1839 ///
1840 /// The drawing obeys the current transform matrix and clipping.
1841 ///
1842 /// All elements of paint: [`crate::PathEffect`], [`crate::MaskFilter`], [`Shader`],
1843 /// [`crate::ColorFilter`], and [`ImageFilter`]; apply to text. By default, draws filled black
1844 /// glyphs.
1845 ///
1846 /// - `count` number of glyphs to draw
1847 /// - `glyphs` the array of glyphIDs to draw
1848 /// - `positions` where to draw each glyph relative to origin
1849 /// - `clusters` array of size count of cluster information
1850 /// - `utf8_text` utf8text supporting information for the glyphs
1851 /// - `origin` the origin of all the positions
1852 /// - `font` typeface, text size and so, used to describe the text
1853 /// - `paint` blend, color, and so on, used to draw
1854 #[allow(clippy::too_many_arguments)]
1855 pub fn draw_glyphs_utf8(
1856 &self,
1857 glyphs: &[GlyphId],
1858 positions: &[Point],
1859 clusters: &[u32],
1860 utf8_text: impl AsRef<str>,
1861 origin: impl Into<Point>,
1862 font: &Font,
1863 paint: &Paint,
1864 ) {
1865 let count = glyphs.len();
1866 if count == 0 {
1867 return;
1868 }
1869 assert_eq!(positions.len(), count);
1870 assert_eq!(clusters.len(), count);
1871 let utf8_text = utf8_text.as_ref().as_bytes();
1872 let origin = origin.into();
1873 unsafe {
1874 sb::C_SkCanvas_drawGlyphs2(
1875 self.native_mut(),
1876 glyphs.as_ptr(),
1877 count,
1878 positions.native().as_ptr(),
1879 clusters.as_ptr(),
1880 utf8_text.as_ptr() as _,
1881 utf8_text.len(),
1882 origin.into_native(),
1883 font.native(),
1884 paint.native(),
1885 )
1886 }
1887 }
1888
1889 /// Draws `count` glyphs, at positions relative to `origin` styled with `font` and `paint`.
1890 ///
1891 /// This function draw glyphs at the given positions relative to the given origin.
1892 /// It does not perform typeface fallback for glyphs not found in the [`crate::Typeface`]] in
1893 /// font.
1894 ///
1895 /// The drawing obeys the current transform matrix and clipping.
1896 ///
1897 /// All elements of paint: [`crate::PathEffect`], [`crate::MaskFilter`], [`Shader`],
1898 /// [`crate::ColorFilter`], and [`ImageFilter`]; apply to text. By default, draws filled black
1899 /// glyphs.
1900 ///
1901 /// - `count` number of glyphs to draw
1902 /// - `glyphs` the array of glyphIDs to draw
1903 /// - `positions` where to draw each glyph relative to origin, either a `&[Point]` or
1904 /// `&[RSXform]` slice
1905 /// - `origin` the origin of all the positions
1906 /// - `font` typeface, text size and so, used to describe the text
1907 /// - `paint` blend, color, and so on, used to draw
1908 pub fn draw_glyphs_at<'a>(
1909 &self,
1910 glyphs: &[GlyphId],
1911 positions: impl Into<GlyphPositions<'a>>,
1912 origin: impl Into<Point>,
1913 font: &Font,
1914 paint: &Paint,
1915 ) {
1916 let count = glyphs.len();
1917 if count == 0 {
1918 return;
1919 }
1920 let positions: GlyphPositions = positions.into();
1921 let origin = origin.into();
1922
1923 let glyphs = glyphs.as_ptr();
1924 let origin = origin.into_native();
1925 let font = font.native();
1926 let paint = paint.native();
1927
1928 match positions {
1929 GlyphPositions::Points(points) => {
1930 assert_eq!(points.len(), count);
1931 unsafe {
1932 sb::C_SkCanvas_drawGlyphs(
1933 self.native_mut(),
1934 glyphs,
1935 count,
1936 points.native().as_ptr(),
1937 origin,
1938 font,
1939 paint,
1940 )
1941 }
1942 }
1943 GlyphPositions::RSXforms(xforms) => {
1944 assert_eq!(xforms.len(), count);
1945 unsafe {
1946 sb::C_SkCanvas_drawGlyphsRSXform(
1947 self.native_mut(),
1948 glyphs,
1949 count,
1950 xforms.native().as_ptr(),
1951 origin,
1952 font,
1953 paint,
1954 )
1955 }
1956 }
1957 }
1958 }
1959
1960 /// Draws [`TextBlob`] blob at `(origin.x, origin.y)`, using clip, [`Matrix`], and [`Paint`]
1961 /// paint.
1962 ///
1963 /// `blob` contains glyphs, their positions, and paint attributes specific to text:
1964 /// [`crate::Typeface`], [`Paint`] text size, [`Paint`] text scale x, [`Paint`] text skew x,
1965 /// [`Paint`] align, [`Paint`] hinting, anti-alias, [`Paint`] fake bold, [`Paint`] font embedded
1966 /// bitmaps, [`Paint`] full hinting spacing, LCD text, [`Paint`] linear text, and [`Paint`]
1967 /// subpixel text.
1968 ///
1969 /// [`TextEncoding`] must be set to [`TextEncoding::GlyphId`].
1970 ///
1971 /// Elements of `paint`: [`crate::PathEffect`], [`crate::MaskFilter`], [`Shader`],
1972 /// [`crate::ColorFilter`], and [`ImageFilter`]; apply to blob.
1973 ///
1974 /// - `blob` glyphs, positions, and their paints' text size, typeface, and so on
1975 /// - `origin` horizontal and vertical offset applied to blob
1976 /// - `paint` blend, color, stroking, and so on, used to draw
1977 ///
1978 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawTextBlob>
1979 pub fn draw_text_blob(
1980 &self,
1981 blob: impl AsRef<TextBlob>,
1982 origin: impl Into<Point>,
1983 paint: &Paint,
1984 ) -> &Self {
1985 let origin = origin.into();
1986 #[cfg(all(feature = "textlayout", feature = "embed-icudtl"))]
1987 crate::icu::init();
1988 unsafe {
1989 self.native_mut().drawTextBlob(
1990 blob.as_ref().native(),
1991 origin.x,
1992 origin.y,
1993 paint.native(),
1994 )
1995 }
1996 self
1997 }
1998
1999 /// Draws [`Picture`] picture, using clip and [`Matrix`]; transforming picture with
2000 /// [`Matrix`] matrix, if provided; and use [`Paint`] `paint` alpha, [`crate::ColorFilter`],
2001 /// [`ImageFilter`], and [`BlendMode`], if provided.
2002 ///
2003 /// If paint is not `None`, then the picture is always drawn into a temporary layer before
2004 /// actually landing on the canvas. Note that drawing into a layer can also change its
2005 /// appearance if there are any non-associative blend modes inside any of the pictures elements.
2006 ///
2007 /// - `picture` recorded drawing commands to play
2008 /// - `matrix` [`Matrix`] to rotate, scale, translate, and so on; may be `None`
2009 /// - `paint` [`Paint`] to apply transparency, filtering, and so on; may be `None`
2010 ///
2011 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawPicture_3>
2012 pub fn draw_picture(
2013 &self,
2014 picture: impl AsRef<Picture>,
2015 matrix: Option<&Matrix>,
2016 paint: Option<&Paint>,
2017 ) -> &Self {
2018 unsafe {
2019 self.native_mut().drawPicture(
2020 picture.as_ref().native(),
2021 matrix.native_ptr_or_null(),
2022 paint.native_ptr_or_null(),
2023 )
2024 }
2025 self
2026 }
2027
2028 /// Draws [`Vertices`] vertices, a triangle mesh, using clip and [`Matrix`].
2029 /// If `paint` contains an [`Shader`] and vertices does not contain tex coords, the shader is
2030 /// mapped using the vertices' positions.
2031 ///
2032 /// [`BlendMode`] is ignored if [`Vertices`] does not have colors. Otherwise, it combines
2033 /// - the [`Shader`] if [`Paint`] contains [`Shader`
2034 /// - or the opaque [`Paint`] color if [`Paint`] does not contain [`Shader`]
2035 ///
2036 /// as the src of the blend and the interpolated vertex colors as the dst.
2037 ///
2038 /// [`crate::MaskFilter`], [`crate::PathEffect`], and antialiasing on [`Paint`] are ignored.
2039 //
2040 /// - `vertices` triangle mesh to draw
2041 /// - `mode` combines vertices' colors with [`Shader`] if present or [`Paint`] opaque color if
2042 /// not. Ignored if the vertices do not contain color.
2043 /// - `paint` specifies the [`Shader`], used as [`Vertices`] texture, and
2044 /// [`crate::ColorFilter`].
2045 ///
2046 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawVertices>
2047 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawVertices_2>
2048 pub fn draw_vertices(&self, vertices: &Vertices, mode: BlendMode, paint: &Paint) -> &Self {
2049 unsafe {
2050 self.native_mut()
2051 .drawVertices(vertices.native(), mode, paint.native())
2052 }
2053 self
2054 }
2055
2056 /// Draws a Coons patch: the interpolation of four cubics with shared corners,
2057 /// associating a color, and optionally a texture [`Point`], with each corner.
2058 ///
2059 /// [`Point`] array cubics specifies four [`Path`] cubic starting at the top-left corner,
2060 /// in clockwise order, sharing every fourth point. The last [`Path`] cubic ends at the
2061 /// first point.
2062 ///
2063 /// Color array color associates colors with corners in top-left, top-right,
2064 /// bottom-right, bottom-left order.
2065 ///
2066 /// If paint contains [`Shader`], [`Point`] array `tex_coords` maps [`Shader`] as texture to
2067 /// corners in top-left, top-right, bottom-right, bottom-left order. If `tex_coords` is
2068 /// `None`, [`Shader`] is mapped using positions (derived from cubics).
2069 ///
2070 /// [`BlendMode`] is ignored if colors is `None`. Otherwise, it combines
2071 /// - the [`Shader`] if [`Paint`] contains [`Shader`]
2072 /// - or the opaque [`Paint`] color if [`Paint`] does not contain [`Shader`]
2073 ///
2074 /// as the src of the blend and the interpolated patch colors as the dst.
2075 ///
2076 /// [`crate::MaskFilter`], [`crate::PathEffect`], and antialiasing on [`Paint`] are ignored.
2077 ///
2078 /// - `cubics` [`Path`] cubic array, sharing common points
2079 /// - `colors` color array, one for each corner
2080 /// - `tex_coords` [`Point`] array of texture coordinates, mapping [`Shader`] to corners;
2081 /// may be `None`
2082 /// - `mode` combines patch's colors with [`Shader`] if present or [`Paint`] opaque color if
2083 /// not. Ignored if colors is `None`.
2084 /// - `paint` [`Shader`], [`crate::ColorFilter`], [`BlendMode`], used to draw
2085 pub fn draw_patch<'a>(
2086 &self,
2087 cubics: &[Point; 12],
2088 colors: impl Into<Option<&'a [Color; 4]>>,
2089 tex_coords: Option<&[Point; 4]>,
2090 mode: BlendMode,
2091 paint: &Paint,
2092 ) -> &Self {
2093 let colors = colors
2094 .into()
2095 .map(|c| c.native().as_ptr())
2096 .unwrap_or(ptr::null());
2097 unsafe {
2098 self.native_mut().drawPatch(
2099 cubics.native().as_ptr(),
2100 colors,
2101 tex_coords
2102 .map(|tc| tc.native().as_ptr())
2103 .unwrap_or(ptr::null()),
2104 mode,
2105 paint.native(),
2106 )
2107 }
2108 self
2109 }
2110
2111 /// Draws a set of sprites from atlas, using clip, [`Matrix`], and optional [`Paint`] paint.
2112 /// paint uses anti-alias, alpha, [`crate::ColorFilter`], [`ImageFilter`], and [`BlendMode`]
2113 /// to draw, if present. For each entry in the array, [`Rect`] tex locates sprite in
2114 /// atlas, and [`RSXform`] xform transforms it into destination space.
2115 ///
2116 /// [`crate::MaskFilter`] and [`crate::PathEffect`] on paint are ignored.
2117 ///
2118 /// xform, tex, and colors if present, must contain the same number of entries.
2119 /// Optional colors are applied for each sprite using [`BlendMode`] mode, treating
2120 /// sprite as source and colors as destination.
2121 /// Optional `cull_rect` is a conservative bounds of all transformed sprites.
2122 /// If `cull_rect` is outside of clip, canvas can skip drawing.
2123 ///
2124 /// * `atlas` - [`Image`] containing sprites
2125 /// * `xform` - [`RSXform`] mappings for sprites in atlas
2126 /// * `tex` - [`Rect`] locations of sprites in atlas
2127 /// * `colors` - one per sprite, blended with sprite using [`BlendMode`]; may be `None`
2128 /// * `count` - number of sprites to draw
2129 /// * `mode` - [`BlendMode`] combining colors and sprites
2130 /// * `sampling` - [`SamplingOptions`] used when sampling from the atlas image
2131 /// * `cull_rect` - bounds of transformed sprites for efficient clipping; may be `None`
2132 /// * `paint` - [`crate::ColorFilter`], [`ImageFilter`], [`BlendMode`], and so on; may be `None`
2133 #[allow(clippy::too_many_arguments)]
2134 pub fn draw_atlas<'a>(
2135 &self,
2136 atlas: &Image,
2137 xform: &[RSXform],
2138 tex: &[Rect],
2139 colors: impl Into<Option<&'a [Color]>>,
2140 mode: BlendMode,
2141 sampling: impl Into<SamplingOptions>,
2142 cull_rect: impl Into<Option<Rect>>,
2143 paint: impl Into<Option<&'a Paint>>,
2144 ) {
2145 let count = xform.len();
2146 assert_eq!(tex.len(), count);
2147 let colors = colors.into();
2148 if let Some(color_slice) = colors {
2149 assert_eq!(color_slice.len(), count);
2150 }
2151 unsafe {
2152 sb::C_SkCanvas_drawAtlas(
2153 self.native_mut(),
2154 atlas.native(),
2155 xform.native().as_ptr(),
2156 count,
2157 tex.native().as_ptr(),
2158 colors.native().as_ptr_or_null(),
2159 mode,
2160 sampling.into().native(),
2161 cull_rect.into().native().as_ptr_or_null(),
2162 paint.into().native_ptr_or_null(),
2163 )
2164 }
2165 }
2166
2167 /// Draws [`Drawable`] drawable using clip and [`Matrix`], concatenated with
2168 /// optional matrix.
2169 ///
2170 /// If [`Canvas`] has an asynchronous implementation, as is the case when it is recording into
2171 /// [`Picture`], then drawable will be referenced, so that [`RCHandle<Drawable>::draw()`] can be
2172 /// called when the operation is finalized. To force immediate drawing, call
2173 /// [`RCHandle<Drawable>::draw()`] instead.
2174 ///
2175 /// - `drawable` custom struct encapsulating drawing commands
2176 /// - `matrix` transformation applied to drawing; may be `None`
2177 ///
2178 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawDrawable>
2179 pub fn draw_drawable(&self, drawable: &mut Drawable, matrix: Option<&Matrix>) {
2180 unsafe {
2181 self.native_mut()
2182 .drawDrawable(drawable.native_mut(), matrix.native_ptr_or_null())
2183 }
2184 }
2185
2186 /// Draws [`Drawable`] drawable using clip and [`Matrix`], offset by `(offset.x, offset.y)`.
2187 ///
2188 /// If [`Canvas`] has an asynchronous implementation, as is the case when it is recording into
2189 /// [`Picture`], then drawable will be referenced, so that [`RCHandle<Drawable>::draw()`] can be
2190 /// called when the operation is finalized. To force immediate drawing, call
2191 /// [`RCHandle<Drawable>::draw()`] instead.
2192 ///
2193 /// - `drawable` custom struct encapsulating drawing commands
2194 /// - `offset` offset into [`Canvas`] writable pixels on x,y-axis
2195 ///
2196 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawDrawable_2>
2197 pub fn draw_drawable_at(&self, drawable: &mut Drawable, offset: impl Into<Point>) {
2198 let offset = offset.into();
2199 unsafe {
2200 self.native_mut()
2201 .drawDrawable1(drawable.native_mut(), offset.x, offset.y)
2202 }
2203 }
2204
2205 /// Associates [`Rect`] on [`Canvas`] when an annotation; a key-value pair, where the key is
2206 /// a UTF-8 string, and optional value is stored as [`Data`].
2207 ///
2208 /// Only some canvas implementations, such as recording to [`Picture`], or drawing to
2209 /// document PDF, use annotations.
2210 ///
2211 /// - `rect` [`Rect`] extent of canvas to annotate
2212 /// - `key` string used for lookup
2213 /// - `value` data holding value stored in annotation
2214 ///
2215 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_drawAnnotation_2>
2216 pub fn draw_annotation(&self, rect: impl AsRef<Rect>, key: &str, value: &Data) -> &Self {
2217 let key = CString::new(key).unwrap();
2218 unsafe {
2219 self.native_mut().drawAnnotation(
2220 rect.as_ref().native(),
2221 key.as_ptr(),
2222 value.native_mut_force(),
2223 )
2224 }
2225 self
2226 }
2227
2228 /// Returns `true` if clip is empty; that is, nothing will draw.
2229 ///
2230 /// May do work when called; it should not be called more often than needed. However, once
2231 /// called, subsequent calls perform no work until clip changes.
2232 ///
2233 /// Returns `true` if clip is empty
2234 ///
2235 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_isClipEmpty>
2236 pub fn is_clip_empty(&self) -> bool {
2237 unsafe { sb::C_SkCanvas_isClipEmpty(self.native()) }
2238 }
2239
2240 /// Returns `true` if clip is [`Rect`] and not empty.
2241 /// Returns `false` if the clip is empty, or if it is not [`Rect`].
2242 ///
2243 /// Returns `true` if clip is [`Rect`] and not empty
2244 ///
2245 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_isClipRect>
2246 pub fn is_clip_rect(&self) -> bool {
2247 unsafe { sb::C_SkCanvas_isClipRect(self.native()) }
2248 }
2249
2250 /// Returns the current transform from local coordinates to the 'device', which for most
2251 /// purposes means pixels.
2252 ///
2253 /// Returns transformation from local coordinates to device / pixels.
2254 pub fn local_to_device(&self) -> M44 {
2255 M44::construct(|m| unsafe { sb::C_SkCanvas_getLocalToDevice(self.native(), m) })
2256 }
2257
2258 /// Throws away the 3rd row and column in the matrix, so be warned.
2259 pub fn local_to_device_as_3x3(&self) -> Matrix {
2260 self.local_to_device().to_m33()
2261 }
2262
2263 /// DEPRECATED
2264 /// Legacy version of [`Self::local_to_device()`], which strips away any Z information, and just
2265 /// returns a 3x3 version.
2266 ///
2267 /// Returns 3x3 version of [`Self::local_to_device()`]
2268 ///
2269 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_getTotalMatrix>
2270 /// Example (C++): <https://fiddle.skia.org/c/@Clip>
2271 #[deprecated(
2272 since = "0.38.0",
2273 note = "use local_to_device() or local_to_device_as_3x3() instead"
2274 )]
2275 pub fn total_matrix(&self) -> Matrix {
2276 let mut matrix = Matrix::default();
2277 unsafe { sb::C_SkCanvas_getTotalMatrix(self.native(), matrix.native_mut()) };
2278 matrix
2279 }
2280
2281 //
2282 // internal helper
2283 //
2284
2285 pub(crate) fn own_from_native_ptr<'lt>(native: *mut SkCanvas) -> Option<OwnedCanvas<'lt>> {
2286 if !native.is_null() {
2287 Some(OwnedCanvas::<'lt>(
2288 ptr::NonNull::new(
2289 Self::borrow_from_native(unsafe { &*native }) as *const _ as *mut _
2290 )
2291 .unwrap(),
2292 PhantomData,
2293 ))
2294 } else {
2295 None
2296 }
2297 }
2298
2299 pub(crate) fn borrow_from_native(native: &SkCanvas) -> &Self {
2300 unsafe { transmute_ref(native) }
2301 }
2302}
2303
2304impl QuickReject<Rect> for Canvas {
2305 /// Returns `true` if [`Rect`] `rect`, transformed by [`Matrix`], can be quickly determined to
2306 /// be outside of clip. May return `false` even though rect is outside of clip.
2307 ///
2308 /// Use to check if an area to be drawn is clipped out, to skip subsequent draw calls.
2309 ///
2310 /// - `rect` [`Rect`] to compare with clip
2311 ///
2312 /// Returns `true` if `rect`, transformed by [`Matrix`], does not intersect clip
2313 ///
2314 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_quickReject>
2315 fn quick_reject(&self, rect: &Rect) -> bool {
2316 unsafe { self.native().quickReject(rect.native()) }
2317 }
2318}
2319
2320impl QuickReject<Path> for Canvas {
2321 /// Returns `true` if `path`, transformed by [`Matrix`], can be quickly determined to be
2322 /// outside of clip. May return `false` even though `path` is outside of clip.
2323 ///
2324 /// Use to check if an area to be drawn is clipped out, to skip subsequent draw calls.
2325 ///
2326 /// - `path` [`Path`] to compare with clip
2327 ///
2328 /// Returns `true` if `path`, transformed by [`Matrix`], does not intersect clip
2329 ///
2330 /// Example (C++): <https://fiddle.skia.org/c/@Canvas_quickReject_2>
2331 fn quick_reject(&self, path: &Path) -> bool {
2332 unsafe { self.native().quickReject1(path.native()) }
2333 }
2334}
2335
2336pub trait SetMatrix {
2337 /// DEPRECATED -- use [`M44`] version
2338 #[deprecated(since = "0.38.0", note = "Use M44 version")]
2339 fn set_matrix(&self, matrix: &Matrix) -> &Self;
2340}
2341
2342impl SetMatrix for Canvas {
2343 /// DEPRECATED -- use [`M44`] version
2344 fn set_matrix(&self, matrix: &Matrix) -> &Self {
2345 unsafe { self.native_mut().setMatrix1(matrix.native()) }
2346 self
2347 }
2348}
2349
2350//
2351// Lattice
2352//
2353
2354pub mod lattice {
2355 //! Divides a [`crate::Bitmap`] or [`crate::Image`] into a rectangular grid for
2356 //! [`crate::Canvas::draw_image_lattice()`]; grid entries on even columns and rows are fixed,
2357 //! the remaining entries scale to fit.
2358 use crate::{Color, IRect, prelude::*};
2359 use skia_bindings::{self as sb, SkCanvas_Lattice};
2360 use std::marker::PhantomData;
2361
2362 /// [`Lattice`] divides [`crate::Bitmap`] or [`crate::Image`] into a rectangular grid.
2363 /// Grid entries on even columns and even rows are fixed; these entries are
2364 /// always drawn at their original size if the destination is large enough.
2365 /// If the destination side is too small to hold the fixed entries, all fixed
2366 /// entries are proportionately scaled down to fit.
2367 /// The grid entries not on even columns and rows are scaled to fit the
2368 /// remaining space, if any.
2369 #[derive(Debug)]
2370 pub struct Lattice<'a> {
2371 /// x-axis values dividing bitmap
2372 pub x_divs: &'a [i32],
2373 /// y-axis values dividing bitmap
2374 pub y_divs: &'a [i32],
2375 /// array of fill types
2376 pub rect_types: Option<&'a [RectType]>,
2377 /// source bounds to draw from
2378 pub bounds: Option<IRect>,
2379 /// array of colors
2380 pub colors: Option<&'a [Color]>,
2381 }
2382
2383 #[derive(Debug)]
2384 pub(crate) struct Ref<'a> {
2385 pub native: SkCanvas_Lattice,
2386 pd: PhantomData<&'a Lattice<'a>>,
2387 }
2388
2389 impl Lattice<'_> {
2390 pub(crate) fn native(&self) -> Ref {
2391 if let Some(rect_types) = self.rect_types {
2392 let rect_count = (self.x_divs.len() + 1) * (self.y_divs.len() + 1);
2393 assert_eq!(rect_count, rect_types.len());
2394 // even though rect types may not include any FixedColor refs,
2395 // we expect the colors slice with a proper size here, this
2396 // saves us for going over the types array and looking for FixedColor
2397 // entries.
2398 assert_eq!(rect_count, self.colors.unwrap().len());
2399 }
2400
2401 let native = SkCanvas_Lattice {
2402 fXDivs: self.x_divs.as_ptr(),
2403 fYDivs: self.y_divs.as_ptr(),
2404 fRectTypes: self.rect_types.as_ptr_or_null(),
2405 fXCount: self.x_divs.len().try_into().unwrap(),
2406 fYCount: self.y_divs.len().try_into().unwrap(),
2407 fBounds: self.bounds.native().as_ptr_or_null(),
2408 fColors: self.colors.native().as_ptr_or_null(),
2409 };
2410 Ref {
2411 native,
2412 pd: PhantomData,
2413 }
2414 }
2415 }
2416
2417 /// Optional setting per rectangular grid entry to make it transparent,
2418 /// or to fill the grid entry with a color.
2419 pub use sb::SkCanvas_Lattice_RectType as RectType;
2420 variant_name!(RectType::FixedColor);
2421}
2422
2423#[must_use]
2424#[derive(Debug)]
2425/// Stack helper class calls [`Canvas::restore_to_count()`] when [`AutoCanvasRestore`]
2426/// goes out of scope. Use this to guarantee that the canvas is restored to a known
2427/// state.
2428pub struct AutoRestoredCanvas<'a> {
2429 canvas: &'a Canvas,
2430 restore: SkAutoCanvasRestore,
2431}
2432
2433impl Deref for AutoRestoredCanvas<'_> {
2434 type Target = Canvas;
2435 fn deref(&self) -> &Self::Target {
2436 self.canvas
2437 }
2438}
2439
2440impl NativeAccess for AutoRestoredCanvas<'_> {
2441 type Native = SkAutoCanvasRestore;
2442
2443 fn native(&self) -> &SkAutoCanvasRestore {
2444 &self.restore
2445 }
2446
2447 fn native_mut(&mut self) -> &mut SkAutoCanvasRestore {
2448 &mut self.restore
2449 }
2450}
2451
2452impl Drop for AutoRestoredCanvas<'_> {
2453 /// Restores [`Canvas`] to saved state. Drop is called when container goes out of scope.
2454 fn drop(&mut self) {
2455 unsafe { sb::C_SkAutoCanvasRestore_destruct(self.native_mut()) }
2456 }
2457}
2458
2459impl AutoRestoredCanvas<'_> {
2460 /// Restores [`Canvas`] to saved state immediately. Subsequent calls and [`Self::drop()`] have
2461 /// no effect.
2462 pub fn restore(&mut self) {
2463 unsafe { sb::C_SkAutoCanvasRestore_restore(self.native_mut()) }
2464 }
2465}
2466
2467pub enum AutoCanvasRestore {}
2468
2469impl AutoCanvasRestore {
2470 // TODO: rename to save(), add a method to Canvas, perhaps named auto_restored()?
2471 /// Preserves [`Canvas::save()`] count. Optionally saves [`Canvas`] clip and [`Canvas`] matrix.
2472 ///
2473 /// - `canvas` [`Canvas`] to guard
2474 /// - `do_save` call [`Canvas::save()`]
2475 ///
2476 /// Returns utility to restore [`Canvas`] state on destructor
2477 pub fn guard(canvas: &Canvas, do_save: bool) -> AutoRestoredCanvas {
2478 let restore = construct(|acr| unsafe {
2479 sb::C_SkAutoCanvasRestore_Construct(acr, canvas.native_mut(), do_save)
2480 });
2481
2482 AutoRestoredCanvas { canvas, restore }
2483 }
2484}
2485
2486#[cfg(test)]
2487mod tests {
2488 use crate::{
2489 AlphaType, Canvas, ClipOp, Color, ColorType, ImageInfo, OwnedCanvas, Rect,
2490 canvas::SaveLayerFlags, canvas::SaveLayerRec, surfaces,
2491 };
2492
2493 #[test]
2494 fn test_raster_direct_creation_and_clear_in_memory() {
2495 let info = ImageInfo::new((2, 2), ColorType::RGBA8888, AlphaType::Unpremul, None);
2496 assert_eq!(8, info.min_row_bytes());
2497 let mut bytes: [u8; 8 * 2] = Default::default();
2498 {
2499 let canvas = Canvas::from_raster_direct(&info, bytes.as_mut(), None, None).unwrap();
2500 canvas.clear(Color::RED);
2501 }
2502
2503 assert_eq!(0xff, bytes[0]);
2504 assert_eq!(0x00, bytes[1]);
2505 assert_eq!(0x00, bytes[2]);
2506 assert_eq!(0xff, bytes[3]);
2507 }
2508
2509 #[test]
2510 fn test_raster_direct_n32_creation_and_clear_in_memory() {
2511 let mut pixels: [u32; 4] = Default::default();
2512 {
2513 let canvas = Canvas::from_raster_direct_n32((2, 2), pixels.as_mut(), None).unwrap();
2514 canvas.clear(Color::RED);
2515 }
2516
2517 // TODO: equals to 0xff0000ff on macOS, but why? Endianness should be the same.
2518 // assert_eq!(0xffff0000, pixels[0]);
2519 }
2520
2521 #[test]
2522 fn test_empty_canvas_creation() {
2523 let canvas = OwnedCanvas::default();
2524 drop(canvas)
2525 }
2526
2527 #[test]
2528 fn test_save_layer_rec_lifetimes() {
2529 let rect = Rect::default();
2530 {
2531 let _rec = SaveLayerRec::default()
2532 .flags(SaveLayerFlags::PRESERVE_LCD_TEXT)
2533 .bounds(&rect);
2534 }
2535 }
2536
2537 #[test]
2538 fn test_make_surface() {
2539 let mut pixels: [u32; 4] = Default::default();
2540 let canvas = Canvas::from_raster_direct_n32((2, 2), pixels.as_mut(), None).unwrap();
2541 let ii = canvas.image_info();
2542 let mut surface = canvas.new_surface(&ii, None).unwrap();
2543 dbg!(&canvas as *const _);
2544 drop(canvas);
2545
2546 let canvas = surface.canvas();
2547 dbg!(canvas as *const _);
2548 canvas.clear(Color::RED);
2549 }
2550
2551 #[test]
2552 fn clip_options_overloads() {
2553 let c = OwnedCanvas::default();
2554 // do_anti_alias
2555 c.clip_rect(Rect::default(), None, true);
2556 // clip_op
2557 c.clip_rect(Rect::default(), ClipOp::Difference, None);
2558 // both
2559 c.clip_rect(Rect::default(), ClipOp::Difference, true);
2560 }
2561
2562 /// Regression test for: <https://github.com/rust-skia/rust-skia/issues/427>
2563 #[test]
2564 fn test_local_and_device_clip_bounds() {
2565 let mut surface =
2566 surfaces::raster(&ImageInfo::new_n32_premul((100, 100), None), 0, None).unwrap();
2567 let _ = surface.canvas().device_clip_bounds();
2568 let _ = surface.canvas().local_clip_bounds();
2569 let _ = surface.canvas().local_to_device();
2570 }
2571}