Flutter中如何使用Canvas绘制对角线样式的虚线?
解决Canvas任意角度虚线绘制问题
你的对角线虚线代码只适用于45度角场景——因为你强制让X、Y轴增量相同,但对于任意角度的线段,必须根据两点间的实际方向计算坐标偏移,才能保证虚线角度和原线段一致。
修正后的完整代码
void _drawDashedLine( Canvas canvas, Paint paint, Size size, Offset p1, Offset p2, ) { const int dashWidth = 5; const int dashSpace = 5; // 计算两点间的水平、垂直距离 final double dx = p2.dx - p1.dx; final double dy = p2.dy - p1.dy; // 计算线段总长度,避免因p1在p2右侧/上方导致循环错误 final double lineLength = sqrt(dx * dx + dy * dy); // 两点重合时直接返回,避免除以0 if (lineLength == 0) return; // 计算单位方向向量:确保X、Y增量按线段比例分配 final double unitX = dx / lineLength; final double unitY = dy / lineLength; double currentX = p1.dx; double currentY = p1.dy; // 记录当前已绘制的长度,判断是否到达终点 double drawnLength = 0; while (drawnLength < lineLength) { // 计算当前虚线段的终点坐标 final double endX = currentX + dashWidth * unitX; final double endY = currentY + dashWidth * unitY; canvas.drawLine(Offset(currentX, currentY), Offset(endX, endY), paint); // 更新下一段虚线的起点位置 drawnLength += dashWidth + dashSpace; currentX += (dashWidth + dashSpace) * unitX; currentY += (dashWidth + dashSpace) * unitY; } }
关键逻辑说明
- 方向向量计算:通过
unitX和unitY确保每一段虚线的偏移都严格遵循原线段的角度比例,不会出现偏差。 - 循环条件优化:用已绘制长度和总线段长度比较,适配p1在p2任意方向的场景(比如从右到左、从下到上的线段)。
- 边界处理:判断两点重合时直接返回,避免数学计算错误。
内容的提问来源于stack exchange,提问作者Kevin Yang
相关产品推荐
相关产品推荐

