不好
这是一个使用GraphicsPath
尝试绘制超过线条末端的箭头并导致System.NotImplementedException
的示例。
GraphicsPath capPath = new GraphicsPath();
capPath.AddLine(0, 8, -5, 0);
capPath.AddLine(-5, 0, 5, 0);
arrowPen.CustomEndCap = new CustomLineCap(capPath, null);
这个失败是因为路径必须与负Y轴相交。但上面的路径只通过原点,实际上并没有碰到负Y轴。
文档中的备注非常重要:
fillPath
和strokePath
参数不能同时使用。一个参数必须传递一个null值。如果两个参数都没有传递null值,则fillPath
将被忽略。如果strokePath
是null
,则fillPath
应该与负y轴相交。
这是其中一种措辞不当的情况。文档说“应该相交”,但我认为它“必须相交”,否则你会得到一个System.NotImplementedException
。这个相交问题仅适用于fillPath
,而不是strokePath
。(文档可能也需要一些图片。)
好
这是一个绘制箭头的GraphicsPath
示例,它可以在线条末端正确地工作。这很可能是大多数人想要绘制的箭头。
![enter image description here](https://istack.dev59.com/CUDB9.webp)
GraphicsPath capPath = new GraphicsPath();
capPath.AddLine(0, 0, -5, -8);
capPath.AddLine(-5, -8, 5, -8);
arrowPen.CustomEndCap = new CustomLineCap(capPath, null); // OK
修复您的示例
一个解决方法是从y中减去triangleHeight
。这将把箭头的尖端放在0,0处(即线的末端的坐标),这可能是您想要的,同时将三角形的底部放在-triangleHeight
处。
float radius = 5.0f;
float triangleSide = 3.0f * radius / (float)Math.Sqrt(3.0f);
float triangleHeight = 3.0f * radius / 2.0f;
GraphicsPath capPath = new GraphicsPath();
capPath.AddLines(new PointF[] {
new PointF(-triangleSide / 2.0f, -triangleHeight),
new PointF(triangleSide / 2.0f, -triangleHeight),
new PointF(0, 0) }
);
arrowPen.CustomEndCap = new CustomLineCap(capPath, null);
你需要的确切修复方法(使用Visual Basic):
Dim points() As PointF = New PointF() { _
New PointF(-triangleSide / 2, -triangleHeight), _
New PointF(triangleSide / 2, -triangleHeight), _
New PointF(0, 0) }
path.AddLines(points)
fillPath
和strokePath
参数不能同时使用。必须传递一个参数为null值。如果两个参数都不传递null值,则fillPath
将被忽略。参考 - Wyck