Skip to main content

BezPath

Struct BezPath 

pub struct BezPath(/* private fields */);
Expand description

A Bézier path.

These docs assume basic familiarity with Bézier curves; for an introduction, see Pomax’s wonderful A Primer on Bézier Curves.

This path can contain lines, quadratics (QuadBez) and cubics (CubicBez), and may contain multiple subpaths.

§Elements and Segments

A Bézier path can be represented in terms of either ‘elements’ (PathEl) or ‘segments’ (PathSeg). Elements map closely to how Béziers are generally used in PostScript-style drawing APIs; they can be thought of as instructions for drawing the path. Segments more directly describe the path itself, with each segment being an independent line or curve.

These different representations are useful in different contexts. For tasks like drawing, elements are a natural fit, but when doing hit-testing or subdividing, we need to have access to the segments.

Conceptually, a BezPath contains zero or more subpaths. Each subpath always begins with a MoveTo, then has zero or more LineTo, QuadTo, and CurveTo elements, and optionally ends with a ClosePath.

Internally, a BezPath is a list of PathEls; as such it implements FromIterator<PathEl> and Extend<PathEl>:

use kurbo::{BezPath, Rect, Shape, Vec2};
let accuracy = 0.1;
let rect = Rect::from_origin_size((0., 0.,), (10., 10.));
// these are equivalent
let path1 = rect.to_path(accuracy);
let path2: BezPath = rect.path_elements(accuracy).collect();

// extend a path with another path:
let mut path = rect.to_path(accuracy);
let shifted_rect = rect + Vec2::new(5.0, 10.0);
path.extend(shifted_rect.to_path(accuracy));

You can iterate the elements of a BezPath with the iter method, and the segments with the segments method:

use kurbo::{BezPath, Line, PathEl, PathSeg, Point, Rect, Shape};
let accuracy = 0.1;
let rect = Rect::from_origin_size((0., 0.,), (10., 10.));
// these are equivalent
let path = rect.to_path(accuracy);
let first_el = PathEl::MoveTo(Point::ZERO);
let first_seg = PathSeg::Line(Line::new((0., 0.), (10., 0.)));
assert_eq!(path.iter().next(), Some(first_el));
assert_eq!(path.segments().next(), Some(first_seg));

In addition, if you have some other type that implements Iterator<Item=PathEl>, you can adapt that to an iterator of segments with the segments free function.

§Advanced functionality

In addition to the basic API, there are several useful pieces of advanced functionality available on BezPath:

  • flatten does Bézier flattening, converting a curve to a series of line segments
  • intersect_line computes intersections of a path with a line, useful for things like subdividing

Implementations§

§

impl BezPath

pub fn new() -> BezPath

Create a new path.

pub fn with_capacity(capacity: usize) -> BezPath

Create a new path with the specified capacity.

This can be useful if you already know how many path elements the path will consist of, to prevent reallocations.

pub fn from_vec(v: Vec<PathEl>) -> BezPath

Create a path from a vector of path elements.

BezPath also implements FromIterator<PathEl>, so it works with collect:

// a very contrived example:
use kurbo::{BezPath, PathEl};

let path = BezPath::new();
let as_vec: Vec<PathEl> = path.into_iter().collect();
let back_to_path: BezPath = as_vec.into_iter().collect();

pub fn pop(&mut self) -> Option<PathEl>

Removes the last PathEl from the path and returns it, or None if the path is empty.

pub fn push(&mut self, el: PathEl)

Push a generic path element onto the path.

pub fn move_to<P>(&mut self, p: P)
where P: Into<Point>,

Push a “move to” element onto the path.

pub fn line_to<P>(&mut self, p: P)
where P: Into<Point>,

Push a “line to” element onto the path.

Will panic with a debug assert when the path is empty and there is no “move to” element on the path.

If line_to is called immediately after close_path then the current subpath starts at the initial point of the previous subpath.

pub fn quad_to<P>(&mut self, p1: P, p2: P)
where P: Into<Point>,

Push a “quad to” element onto the path.

Will panic with a debug assert when the path is empty and there is no “move to” element on the path.

If quad_to is called immediately after close_path then the current subpath starts at the initial point of the previous subpath.

pub fn curve_to<P>(&mut self, p1: P, p2: P, p3: P)
where P: Into<Point>,

Push a “curve to” element onto the path.

Will panic with a debug assert when the path is empty and there is no “move to” element on the path.

If curve_to is called immediately after close_path then the current subpath starts at the initial point of the previous subpath.

pub fn close_path(&mut self)

Push a “close path” element onto the path.

Will panic with a debug assert when the path is empty and there is no “move to” element on the path.

pub fn into_elements(self) -> Vec<PathEl>

Consumes the BezPath and returns a vector of PathEls.

pub fn elements(&self) -> &[PathEl]

Get the path elements.

For owned elements, see into_elements.

pub fn elements_mut(&mut self) -> &mut [PathEl]

Get the path elements (mut version).

pub fn iter(&self) -> impl Iterator<Item = PathEl> + Clone

Returns an iterator over the path’s elements.

pub fn segments(&self) -> impl Iterator<Item = PathSeg> + Clone

Iterate over the path segments.

pub fn truncate(&mut self, len: usize)

Shorten the path, keeping the first len elements.

pub fn get_seg(&self, ix: usize) -> Option<PathSeg>

Get the segment at the given element index.

If you need to access all segments, segments provides a better API. This is intended for random access of specific elements, for clients that require this specifically.

note: This returns the segment that ends at the provided element index. In effect this means it is 1-indexed: since no segment ends at the first element (which is presumed to be a MoveTo) get_seg(0) will always return None.

pub fn is_empty(&self) -> bool

Returns true if the path contains no segments.

pub fn apply_affine(&mut self, affine: Affine)

Apply an affine transform to the path.

pub fn is_finite(&self) -> bool

Is this path finite?

pub fn is_nan(&self) -> bool

Is this path NaN?

pub fn control_box(&self) -> Rect

Returns a rectangle that conservatively encloses the path.

Unlike the bounding_box method, this uses control points directly rather than computing tight bounds for curve elements.

pub fn current_position(&self) -> Option<Point>

Returns current position in the path, if path is not empty.

This is different from calling PathEl::end_point on the last entry of BezPath::elements: this method handles PathEl::ClosePath, by finding the first point of our last subpath, hence the time complexity is O(n).

pub fn subpaths(&self) -> impl Iterator<Item = &[PathEl]>

Returns an iterator over the subpaths of this path. See Elements and Segments for more information.

pub fn reverse_subpaths(&self) -> BezPath

Returns a new path with the winding direction of all subpaths reversed.

§

impl BezPath

pub fn from_path_segments(segments: impl Iterator<Item = PathSeg>) -> BezPath

Create a BezPath with segments corresponding to the sequence of PathSegs

pub fn to_svg(&self) -> String

Convert the path to an SVG path string representation.

The current implementation doesn’t take any special care to produce a short string (reducing precision, using relative movement).

pub fn write_to<W>(&self, writer: W) -> Result<(), Error>
where W: Write,

Write the SVG representation of this path to the provided buffer.

pub fn from_svg(data: &str) -> Result<BezPath, SvgParseError>

Try to parse a bezier path from an SVG path element.

This is implemented on a best-effort basis, intended for cases where the user controls the source of paths, and is not intended as a replacement for a general, robust SVG parser.

Trait Implementations§

§

impl Clone for BezPath

§

fn clone(&self) -> BezPath

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for BezPath

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for BezPath

§

fn default() -> BezPath

Returns the “default value” for a type. Read more
§

impl Extend<PathEl> for BezPath

§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = PathEl>,

Add the items from the iterator to this path.

Note that if you’re attempting to make a continuous path, you will generally want to ensure that the iterator does not contain any MoveTo or ClosePath elements. Note especially that many (open) shapes will start with a MoveTo if you use their path_elements function. Some shapes have alternatives for this use case, such as Arc::append_iter.

Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
§

impl FromIterator<PathEl> for BezPath

§

fn from_iter<T>(iter: T) -> BezPath
where T: IntoIterator<Item = PathEl>,

Creates a value from an iterator. Read more
§

impl<'a> IntoIterator for &'a BezPath

Allow iteration over references to BezPath.

Note: the semantics are slightly different from simply iterating over the slice, as it returns PathEl items, rather than references.

§

type Item = PathEl

The type of the elements being iterated over.
§

type IntoIter = Cloned<Iter<'a, PathEl>>

Which kind of iterator are we turning this into?
§

fn into_iter(self) -> <&'a BezPath as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
§

impl IntoIterator for BezPath

§

type Item = PathEl

The type of the elements being iterated over.
§

type IntoIter = IntoIter<PathEl>

Which kind of iterator are we turning this into?
§

fn into_iter(self) -> <BezPath as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
§

impl Mul<&BezPath> for Affine

§

type Output = BezPath

The resulting type after applying the * operator.
§

fn mul(self, other: &BezPath) -> BezPath

Performs the * operation. Read more
§

impl Mul<&BezPath> for TranslateScale

§

type Output = BezPath

The resulting type after applying the * operator.
§

fn mul(self, other: &BezPath) -> BezPath

Performs the * operation. Read more
§

impl Mul<BezPath> for Affine

§

type Output = BezPath

The resulting type after applying the * operator.
§

fn mul(self, other: BezPath) -> BezPath

Performs the * operation. Read more
§

impl Mul<BezPath> for TranslateScale

§

type Output = BezPath

The resulting type after applying the * operator.
§

fn mul(self, other: BezPath) -> BezPath

Performs the * operation. Read more
§

impl PartialEq for BezPath

§

fn eq(&self, other: &BezPath) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl Shape for BezPath

§

fn area(&self) -> f64

Signed area.

§

fn winding(&self, pt: Point) -> i32

Winding number of point.

§

type PathElementsIter<'iter> = Copied<Iter<'iter, PathEl>>

The iterator returned by the path_elements method.
§

fn path_elements( &self, _tolerance: f64, ) -> <BezPath as Shape>::PathElementsIter<'_>

Returns an iterator over this shape expressed as PathEls; that is, as Bézier path elements. Read more
§

fn to_path(&self, _tolerance: f64) -> BezPath

Convert to a Bézier path. Read more
§

fn into_path(self, _tolerance: f64) -> BezPath

Convert into a Bézier path. Read more
§

fn perimeter(&self, accuracy: f64) -> f64

Total length of perimeter.
§

fn bounding_box(&self) -> Rect

The smallest rectangle that encloses the shape.
§

fn as_path_slice(&self) -> Option<&[PathEl]>

If the shape is stored as a slice of path elements, make that available. Read more
§

fn path_segments(&self, tolerance: f64) -> Segments<Self::PathElementsIter<'_>> ⓘ

Returns an iterator over this shape expressed as Bézier path segments (PathSegs). Read more
§

fn contains(&self, pt: Point) -> bool

Returns true if the Point is inside this shape. Read more
§

fn as_line(&self) -> Option<Line>

If the shape is a line, make it available.
§

fn as_rect(&self) -> Option<Rect>

If the shape is a rectangle, make it available.
§

fn as_rounded_rect(&self) -> Option<RoundedRect>

If the shape is a rounded rectangle, make it available.
§

fn as_circle(&self) -> Option<Circle>

If the shape is a circle, make it available.
§

impl StructuralPartialEq for BezPath

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AnyEq for T
where T: Any + PartialEq,

§

fn equals(&self, other: &(dyn Any + 'static)) -> bool

§

fn as_any(&self) -> &(dyn Any + 'static)

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync> ⓘ

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> NoneValue for T
where T: Default,

§

type NoneType = T

§

fn null_value() -> T

The none-equivalent value.
§

impl<'a, T> ParamCurveMoments<'a> for T
where T: 'a, &'a T: IntoIterator<Item = PathEl>,

§

fn moments(&'a self) -> Moments

Returns the moment integrals for the path using Green’s theorem.
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<T, S> SimdFrom<T, S> for T
where S: Simd,

§

fn simd_from(_simd: S, value: T) -> T

§

impl<F, T, S> SimdInto<T, S> for F
where T: SimdFrom<F, S>, S: Simd,

§

fn simd_into(self, simd: S) -> T

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where T: 'static,

§

impl<T> Fruit for T
where T: Send + Downcast,

§

impl<T> MaybeSendSync for T
where T: Send + Sync + ?Sized,

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T

§

impl<T> WasmNotSync for T
where T: Sync,