关于CupertinoSwitch的thumb添加阴影

373 阅读1分钟

flutter自带的CupertinoSwitch的thumb是无阴影的,但是开发的时候设计图给的有阴影,自定义thumb后还是无阴影,最后发现是CupertinoSwitch将边界外的阴影部分截掉了

Switch.gif

先自定义thumb的阴影,拷贝一份thumb_painter文件到本地,修改类名,然后将下面画阴影的方法添加进去

void paint(Canvas canvas, Rect rect) {
 ...
 //canvas自带的画阴影方法
 canvas.drawShadow(
     Path()..addArc(rect, 1, 2 * pi),
     Colors.grey.withOpacity(0.3),
     6,
     true
 );
 canvas.drawRRect(rrect, Paint()..color = color);

}

拷贝一下CupertinoSwitch到本地,并修改类名,用下面代码替换527-529行代码

///这个方法是限制里面的内容只在trackRRect这个范围内绘制,就算是阴影超出部分也会被切掉
// context.pushClipRRect(false, Offset.zero, thumbBounds, trackRRect, (PaintingContext innerContext, Offset offset) {
//   const MCupertinoThumbPainter.switchThumb().paint(innerContext.canvas, thumbBounds);
// });
const MCupertinoThumbPainter.switchThumb().paint(canvas, thumbBounds);

代码地址:github.com/justyouzxy/…