首页 > 解决方案 > 在 C# windows 窗体中绘制一条直线

问题描述

我有一个简单的 Windows 窗体程序,它允许用户在图片框中绘制直线。有一条线,但它超出了图片框并且在其中不可见(就像我附上的图片一样)。我怎样才能让它只出现在图片框中。这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;

namespace LinePOD
{
public partial class LineTest : Form
{
    public LineTest()
    {
        InitializeComponent();
    }

    Point p1 = new Point();
    Point p2 = new Point();
    Pen pen = new Pen(Color.Magenta, 10);
    private void LineTest_Load(object sender, EventArgs e)
    {

    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            p1 = e.Location;
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {

        if (e.Button == MouseButtons.Left)
        {
            p2 = e.Location;
            Graphics g = this.CreateGraphics();
            g.DrawLine(pen, p1, p2);
        }
    }

    private void pictureBox1_Click(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        pictureBox1.BackColor = Color.Aqua;
    }
}

}

标签: c#visual-studiowinforms

解决方案


您可以创建一个与 PictureBox 大小相同的位图,并在 PictureBox 的 Paint 事件中绘制该位图。然后在鼠标事件中为位图绘制线条。这会保留 Windows 最小化/恢复事件中的行。为了方便起见,我放了整个代码:

public partial class Form1 : Form
{
    Bitmap bitmap;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        bitmap = new Bitmap(pictureBox1.ClientSize.Width, 
        pictureBox1.ClientSize.Height, 
        System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    }

    Point p1 = new Point();
    Point p2 = new Point();
    Pen pen = new Pen(Color.Magenta, 10);

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            p1 = e.Location;
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {

        if (e.Button == MouseButtons.Left)
        {
            p2 = e.Location;
            Graphics g = Graphics.FromImage(bitmap);
            g.DrawLine(pen, p1, p2);
            pictureBox1.Invalidate();
            g.Dispose();
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        pictureBox1.BackColor = Color.Aqua;
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
    }
}

推荐阅读