path_kit/dash_path_effect.rs
1//! 虚线路径效果。Dash path effect.
2//!
3//! ⚠️ **实验性 / Experimental**: sk_sp 生命周期与 Rust 集成尚不完善,使用时需注意。
4//! ⚠️ **Experimental**: sk_sp lifecycle integration with Rust is incomplete; use with caution.
5
6use crate::path::Path;
7use crate::pathkit;
8
9/// 虚线路径效果,将路径描边转为虚线。
10/// Dash path effect for stroked paths (on/off intervals).
11pub struct DashPathEffect {
12 inner: pathkit::sk_sp<pathkit::SkPathEffect>,
13}
14
15impl DashPathEffect {
16 /// 创建虚线效果。Creates a dash effect.
17 ///
18 /// `intervals`: 交替的 on/off 长度,如 [10.0, 20.0] 表示 10 像素 on、20 像素 off
19 /// `intervals`: on/off lengths, e.g. [10.0, 20.0] = 10px on, 20px off
20 /// `phase`: 相位偏移
21 /// `phase`: phase offset into the pattern
22 pub fn new(intervals: &[f32], phase: f32) -> Option<Self> {
23 if intervals.is_empty() || intervals.len() % 2 != 0 {
24 return None;
25 }
26 let inner = unsafe {
27 pathkit::SkDashPathEffect_Make(
28 intervals.as_ptr(),
29 intervals.len() as i32,
30 phase,
31 )
32 };
33 if inner.fPtr.is_null() {
34 return None;
35 }
36 Some(Self { inner })
37 }
38
39 /// 应用到路径。Applies effect to path (requires stroke width).
40 ///
41 /// `path`: 输入路径
42 /// `stroke_width`: 描边宽度(虚线仅对描边路径有效)
43 /// `path`: input path
44 /// `stroke_width`: stroke width (dash only affects stroked paths)
45 pub fn filter_path(&self, path: &Path, stroke_width: f32) -> Option<Path> {
46 let mut dst = Path::new();
47 let mut rec = unsafe {
48 pathkit::SkStrokeRec::new(pathkit::SkStrokeRec_InitStyle::kHairline_InitStyle)
49 };
50 unsafe {
51 rec.setStrokeStyle(stroke_width, false);
52 }
53 let bounds = path.tight_bounds();
54 let cull: pathkit::SkRect = bounds.into();
55 let ok = unsafe {
56 pathkit::SkPathEffect_filterPath(
57 self.inner.fPtr,
58 dst.as_raw_mut() as *mut _,
59 path.as_raw() as *const _,
60 &mut rec as *mut _,
61 &cull as *const _,
62 )
63 };
64 if ok {
65 Some(dst)
66 } else {
67 None
68 }
69 }
70}