在C#中使用鼠标单击画框上画线 [英] Draw lines on a picturebox using mouse clicks in C#

查看:767
本文介绍了在C#中使用鼠标单击画框上画线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个程序,它将在 picturebox ,使用鼠标点击该线条的绘制位置。这是我现在的代码:

pre $ $ code public partial class Form1:Form
{
int Drawshape;

私人点p1,p2;
列表< Point> p1List = new List< Point>();
列表< Point> p2List = new List< Point>();

public Form1()
{
InitializeComponent();
pictureBox1.Image = new Bitmap(pictureBox1.Width,pictureBox1.Height);


private void button1_Click(object sender,EventArgs e)
{
Drawshape = 1;
}

private void button2_Click(object sender,EventArgs e)
{
Drawshape = 2;

$ b private void pictureBox1_MouseDown(object sender,MouseEventArgs e)
{
if(Drawshape == 1)
{
if( p1.X == 0)
{
p1.X = eX;
p1.Y = e.Y;
}
else
{
p2.X = e.X;
p2.Y = e.Y;

p1List.Add(p1);
p2List.Add(p2);

Invalidate();
p1.X = 0;



$ b private void pictureBox1_Paint(object sender,PaintEventArgs e)
{
Graphics G = Graphics.FromImage(pictureBox1 。图片);
if(Drawshape == 1)
{
using(var p = new Pen(Color.Blue,4))
{
for(int x = 0 ; x {
G.DrawLine(p,p1List [x],p2List [x]);




code


那一刻它不允许我在画箱上画画。

解决方案

更改 Invalidate(); to pictureBox1.Invalidate();


I'm trying to make a program that will draw lines over a picturebox using mouse clicks for the locations of where the line is to be drawn from and to. This is my current code:

public partial class Form1 : Form
{
    int Drawshape;

    private Point p1, p2;
    List<Point> p1List = new List<Point>();
    List<Point> p2List = new List<Point>();

    public Form1()
    {
        InitializeComponent();
        pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Drawshape = 1;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Drawshape = 2;
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (Drawshape == 1)
        {
            if (p1.X == 0)
            {
                p1.X = e.X;
                p1.Y = e.Y;
            }
            else
            {
                p2.X = e.X;
                p2.Y = e.Y;

                p1List.Add(p1);
                p2List.Add(p2);

                Invalidate();
                p1.X = 0;
            }
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Graphics G = Graphics.FromImage(pictureBox1.Image);
        if (Drawshape == 1)
        {
            using (var p = new Pen(Color.Blue, 4))
            {
                for (int x = 0; x < p1List.Count; x++)
                {
                    G.DrawLine(p, p1List[x], p2List[x]);
                }
            }
        }
    }

At the moment it doesn't allow me to draw on the picturebox at all. How would that be possible?

解决方案

Change Invalidate(); to pictureBox1.Invalidate();

这篇关于在C#中使用鼠标单击画框上画线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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