c# - 在 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;
}
}
}
解决方案
您可以创建一个与 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);
}
}
推荐阅读
- python - 多对多字段上的 Django 唯一
- sql - 将第一个单词提取到第一个空格 - POSTGRES
- discord - How do I add a mention ability when using a command such us "rate @user" discord.js?
- ruby - 如何编写使用 with 发送参数的方法模拟
- c++ - 对 CLSID_FileOpenDialog 的引用不足 - Mingw64
- angular - 如何使用双向绑定以角度同时检查用户名和电子邮件
- python - Python discord bot,等待消息未按预期工作
- datatable - 从另一个表动态生成 Power BI 中的新表
- storybook - 如何在根级别设置故事书 lerna monorepo
- python - 从html重新创建形状文件?