开发者

HowTo: Draw a line with an arrow?

I have the following code, that draws a line with a (very) small arrow...

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Pen p = new Pen(Color.Black);
        p.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;

        e.Graphics.DrawLine(p, 10, 10, 100, 100);
        p.Dispose();
    }

I want to draw a big arrow (circle, square, triangle etc...), keeping the s开发者_高级运维ame line width.

Is it possible?


You'd want to use a CustomLineCap with a GraphicsPath. Here's an example:

using(Pen p = new Pen(Color.Black))
using(GraphicsPath capPath = new GraphicsPath())
{
    // A triangle
    capPath.AddLine(-20, 0, 20, 0);
    capPath.AddLine(-20, 0, 0, 20);
    capPath.AddLine(0, 20, 20, 0);

    p.CustomEndCap = new System.Drawing.Drawing2D.CustomLineCap(null, capPath);

    e.Graphics.DrawLine(p, 0, 50, 100, 50);
}

You want to "design" your cap with a line going top-to-bottom and from (0, 0) to get the correct coordinates.

EDIT: I just wanted to mention that you can also use AdjustableArrowCap to draw an arrow of a specific size and fill it but because you mentioned the requirement for other shapes, I've used a CustomLineCap.


As TheCloudlessSky mentioned, AdjustableArrowCap can be used to draw the arrow head.

public static void DrawLine(Graphics g, Point from, Point to)
{
    var pen = new Pen(Color.Black, 1);

    pen.CustomEndCap = new AdjustableArrowCap(5, 5);

    g.DrawLine(pen, from, to);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜