Skip to main content

path_kit/
dash_path_effect.rs

1//! 虚线路径效果。Dash path effect.
2
3use crate::bridge::ffi;
4use crate::path::Path;
5use crate::stroke_rec::StrokeRec;
6use cxx::UniquePtr;
7
8/// 虚线路径效果,将路径描边转为虚线。
9/// Dash path effect for stroked paths (on/off intervals).
10pub struct DashPathEffect {
11    inner: UniquePtr<ffi::PathEffectHolder>,
12}
13
14impl DashPathEffect {
15    /// 创建虚线效果。Creates a dash effect.
16    ///
17    /// `intervals`: 交替的 on/off 长度,如 [10.0, 20.0] 表示 10 像素 on、20 像素 off
18    /// `intervals`: on/off lengths, e.g. [10.0, 20.0] = 10px on, 20px off
19    /// `phase`: 相位偏移
20    /// `phase`: phase offset into the pattern
21    pub fn new(intervals: &[f32], phase: f32) -> Option<Self> {
22        if intervals.is_empty() || !intervals.len().is_multiple_of(2) {
23            return None;
24        }
25        let inner = ffi::dash_effect_make(intervals, phase);
26        if inner.is_null() {
27            return None;
28        }
29        Some(Self { inner })
30    }
31
32    /// 应用到路径。Applies effect to path (requires stroke width).
33    ///
34    /// `path`: 输入路径
35    /// `stroke_width`: 描边宽度(虚线仅对描边路径有效)
36    /// `path`: input path
37    /// `stroke_width`: stroke width (dash only affects stroked paths)
38    ///
39    /// 失败时返回 `None`。Returns `None` on failure.
40    pub fn filter_path(&self, path: &Path, stroke_width: f32) -> Option<Path> {
41        let mut dst = Path::new();
42        let mut rec = StrokeRec::new_stroke(stroke_width, false);
43        let bounds = path.tight_bounds();
44        let cull: ffi::Rect = bounds.into();
45        let ok = ffi::path_effect_filter(
46            self.inner.as_ref().expect("PathEffect"),
47            dst.as_raw_pin_mut(),
48            path.as_raw(),
49            rec.pin_holder_mut(),
50            &cull,
51        );
52        if ok {
53            Some(dst)
54        } else {
55            None
56        }
57    }
58}