如何添加阴影自定义绘制小部件?



我用自定义画器画了一个三角形,我想给它添加阴影。

class TrianglePainter extends CustomPainter {
final Color strokeColor;
final PaintingStyle paintingStyle;
final double strokeWidth;
TrianglePainter({this.strokeColor = Colors.black, this.strokeWidth = 3, this.paintingStyle = PaintingStyle.stroke});
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..color = strokeColor
..strokeWidth = strokeWidth
..style = paintingStyle;
canvas.drawPath(getTrianglePath(size.width, size.height), paint);
}
Path getTrianglePath(double x, double y) {
return Path()
..moveTo(x*(1-sqrt(3)/4)/2+x/15, y/4)
..lineTo(x*(1-sqrt(3)/4)/2+x/15, y*3/4)
..lineTo(x*(1+sqrt(3)/4)/2+x/15, y/2)
..lineTo(x*(1-sqrt(3)/4)/2+x/15, y/4);

}
@override
bool shouldRepaint(TrianglePainter oldDelegate) {
return oldDelegate.strokeColor != strokeColor ||
oldDelegate.paintingStyle != paintingStyle ||
oldDelegate.strokeWidth != strokeWidth;
}

}

上面的是三角形绘制代码。

如何添加阴影呢?或者有没有办法用容器来画三角形?我希望我可以自定义阴影的x, y,模糊和扩散值。谢谢你的阅读,我将等待你的建议:)

使用,此通用自定义ShapeBorder

class ShapeBuilder extends ShapeBorder {
final Path Function(Rect rect, {TextDirection textDirection}) pathBuilder;
ShapeBuilder(this.pathBuilder);
@override EdgeInsetsGeometry get dimensions => null;
@override Path getInnerPath(Rect rect, {TextDirection textDirection}) => null;
@override void paint(Canvas canvas, Rect rect, {TextDirection textDirection}) => null;
@override ShapeBorder scale(double t) => null;
@override
Path getOuterPath(Rect rect, {TextDirection textDirection}) => pathBuilder(rect, textDirection: textDirection);
}

现在,使用以下"builder"功能:

Path trangle(Rect rect, {TextDirection textDirection}) {
return Path()
..moveTo(rect.topCenter.dx, rect.topCenter.dy)
..lineTo(rect.bottomRight.dx, rect.bottomRight.dy)
..lineTo(rect.bottomLeft.dx, rect.bottomLeft.dy);
}

你可以这样使用:

Container(
width: 64,
height: 64,
decoration: ShapeDecoration(
color: Colors.white,
shape: ShapeBuilder(trangle),
shadows: [
BoxShadow(color: Colors.black, blurRadius: 4.0, offset: Offset(2, 2)),
],
),
),

最新更新