欢迎大家加入开源鸿蒙跨平台社区Flutter SVG 图片 Demo本文介绍在 Flutter鸿蒙跨平台项目中不依赖任何第三方库使用纯 Dart CustomPainter实现 SVG 图形渲染、属性编辑、动画播放的核心要点。一、方案选择纯 Dart 替代 flutter_svgflutter_svg等主流 SVG 插件在鸿蒙平台存在兼容问题因此采用CustomPainter直接绘制矢量图形实现零依赖、完全跨平台。class_ShapePainterextendsCustomPainter{finalvoidFunction(Canvas,Size)draw;_ShapePainter(this.draw);overridevoidpaint(Canvascanvas,Sizesize)draw(canvas,size);overrideboolshouldRepaint(_)false;}将绘制逻辑作为函数传入实现高度复用。二、整体结构使用IndexedStackNavigationBar实现三 Tab 布局body:IndexedStack(index:_tabIndex,children:const[_GalleryTab(),_EditorTab(),_AnimTab()],),三、常用 SVG 图形绘制星形多边形路径通过奇偶半径交替计算顶点绘制星形Path_starPath(double cx,double cy,double outerR,double innerR,int points){finalpathPath();for(int i0;ipoints*2;i){finalri.isEven?outerR:innerR;finalanglepi*i/points-pi/2;finalxcxr*cos(angle);finalycyr*sin(angle);i0?path.moveTo(x,y):path.lineTo(x,y);}returnpath..close();}心形贝塞尔曲线使用cubicTo三次贝塞尔曲线构造心形轮廓path.moveTo(w*0.5,h*0.85);path.cubicTo(w*0.1,h*0.6,w*0.0,h*0.3,w*0.25,h*0.2);path.cubicTo(w*0.4,h*0.1,w*0.5,h*0.2,w*0.5,h*0.3);// 对称右侧...螺旋线参数方程阿基米德螺旋半径随角度线性增长for(int i0;isteps;i){finalti/steps;finalanglet*turns*2*pi;finalrt*maxRadius;// 半径线性增长finalxcxr*cos(angle);finalycyr*sin(angle);i0?path.moveTo(x,y):path.lineTo(x,y);}四、SVG 属性编辑器通过Paint对象的参数实时控制填充、描边、透明度finalfillPaint()..colorfillColor..stylePaintingStyle.fill;finalstrokePaint()..colorstrokeColor..stylePaintingStyle.stroke..strokeWidthstrokeWidth;配合Transform.rotateTransform.scaleOpacity实现旋转、缩放、透明度的实时预览Opacity(opacity:_opacity,child:Transform.rotate(angle:_rotation*pi/180,child:Transform.scale(scale:_scale,child:CustomPaint(...)),),),五、SVG 动画使用AnimationController 多个Tween驱动旋转、缩放、颜色动画_ctrlAnimationController(vsync:this,duration:constDuration(seconds:2))..repeat(reverse:true);_rotateAnimTween(begin:0.0,end:2*pi).animate(_ctrl);_scaleAnimTween(begin:0.5,end:1.5).animate(_ctrl);_colorAnimColorTween(begin:Colors.blue,end:Colors.orange).animate(_ctrl);AnimatedBuilder监听动画值按模式选择性应用变换AnimatedBuilder(animation:_ctrl,builder:(_,__){finalangle(_animMode0||_animMode3)?_rotateAnim.value:0.0;finalscale(_animMode1||_animMode3)?_scaleAnim.value:1.0;finalcolor(_animMode2||_animMode3)?_colorAnim.value!:Colors.blue;returnTransform.rotate(angle:angle,child:Transform.scale(scale:scale,...));},),六、花瓣动画绘制在CustomPainter中通过progress参数驱动花瓣旋转和圆弧进度for(int i0;ipetalCount;i){finalangle2*pi*i/petalCountprogress*2*pi;// 随进度旋转canvas.drawCircle(Offset(cxr*cos(angle),cyr*sin(angle)),r*0.35,paint);}// 外圆弧进度canvas.drawArc(rect,-pi/2,2*pi*progress,false,arcPaint);总结模块核心技术图形绘制CustomPainterCanvasAPI路径构造Path.cubicTo/lineTo/ 参数方程属性编辑Paint参数 TransformOpacity动画驱动AnimationControllerTweenAnimatedBuilder平台兼容纯 Dart 实现无需第三方插件完全支持鸿蒙