在 C# 中的图片框上绘制箭头 [英] Draw an Arrow on a Picturebox in C#

查看:140
本文介绍了在 C# 中的图片框上绘制箭头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从一个鼠标单击位置绘制一个直线箭头到另一个位置,就像您在 PowerPoint 中所做的那样.它还需要能够在 PictureBox 上绘图.

I want to be able to draw a straight arrow from one mouse click location to another, as if you were doing it in PowerPoint. It needs to be able to draw on a PictureBox as well.

推荐答案

这里是一些基本代码,用于在图片框中从鼠标向下到当前位置绘制线条.
您只需要为箭头绘制更多线条或三角形即可.

Here is some basic code to draw lines in a picturebox from mouse down to current location.
You just need to draw some more lines or a triangle for the arrow head.

public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
    public Form1()
    {
        InitializeComponent();

        // 
        // pictureBox1
        // 
        this.pictureBox1.Location = new System.Drawing.Point(0, 0);
        this.pictureBox1.Name = "pictureBox1";
        this.pictureBox1.Size = new System.Drawing.Size(231, 235);
        this.pictureBox1.TabIndex = 0;
        this.pictureBox1.TabStop = false;
        this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
        this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
        this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove);
        this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp);
        this.Controls.Add(this.pictureBox1);
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition);
            foreach (var line in lines)
            {
                g.DrawLine(Pens.Black, line.Item1, line.Item2);
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition));
        }
        isMoving = false;
    }
}

这篇关于在 C# 中的图片框上绘制箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆