我有一个简单的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;
}
}
}
您可以创建具有相同大小的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);
}
}