C# 在现有图像上使用笔刷绘制
我已经将下面的代码嵌入到一个项目中,其中一个用户希望用画笔在图片上画画。问题是,如果一个用户为一个主面板编写这段代码,一切都会顺利进行,但由于我想将其用于现有图像,我看不到画笔。我想画笔会画画,但这是前景/背景的问题C# 在现有图像上使用笔刷绘制,c#,graphics,paint,brush,toolbox,C#,Graphics,Paint,Brush,Toolbox,我已经将下面的代码嵌入到一个项目中,其中一个用户希望用画笔在图片上画画。问题是,如果一个用户为一个主面板编写这段代码,一切都会顺利进行,但由于我想将其用于现有图像,我看不到画笔。我想画笔会画画,但这是前景/背景的问题 //the first line goes to the main form - under the initialize component graphics = DisplayPicturebox.CreateGraphics(); bool draw = false; G
//the first line goes to the main form - under the initialize component
graphics = DisplayPicturebox.CreateGraphics();
bool draw = false;
Graphics graphics;
private void DisplayPicturebox_MouseDown(object sender, MouseEventArgs e)
{
draw = true;
}
private void DisplayPicturebox_MouseUp(object sender, MouseEventArgs e)
{
draw = false;
}
private void DisplayPicturebox_MouseMove(object sender, MouseEventArgs e)
{
if (draw)
{
//create a brush:
SolidBrush MysolidBrush = new SolidBrush(Color.Red);
graphics.FillEllipse(MysolidBrush, e.X, e.Y,
Convert.ToInt32(toolStripTextBox1.Text),
Convert.ToInt32(toolStripTextBox1.Text));
}
}
这里需要注意的几个重要事项:
- 图形需要在管道中处理或以某种方式保存,以便重新绘制不会消除用户所做的更改
- 保持图形上下文无限期地打开是个坏主意。您应该打开上下文日志,以便将所需内容绘制到缓冲区或屏幕,然后关闭该上下文
- 如果你想使用屏幕外的缓冲区,你需要记住你正在使用的坐标系(“屏幕”对“控制”,对“缓冲”)。如果你感到困惑,你可能看不到你所期望的
记住这些概念,您可以考虑以下代码的更改:
// at the beginning of your class declare an offscreen buffer
private System.Drawing.Bitmap buffer;
// .. later create it in the constructor
public Form1() {
InitializeComponent();
// use the w/h of the picture box here
buffer = new System.Drawing.Bitmap(picBox.Width, picBox.Height);
}
// in the designer add a paint event for the picture box:
private picBox_Paint(object sender, System.Windows.Forms.PaintEventArgs e) {
e.Graphics.DrawImageUnscaled(buffer);
}
// finally, your slightly modified painting routine...
private picBox__MouseMove(object sender, MouseEventArgs e)
{
if (draw)
{
using (var context = System.Drawing.Graphics.FromImage(buffer)) {
//create a brush:
SolidBrush MysolidBrush = new SolidBrush(Color.Red);
graphics.FillEllipse(MysolidBrush, e.X, e.Y,
Convert.ToInt32(toolStripTextBox1.Text),
Convert.ToInt32(toolStripTextBox1.Text));
}
}
}
这并不意味着是完美的代码,但通用模板应该可以工作,让您更接近我认为您正在寻找的内容。希望对你有所帮助 试试这个,修改mousemove事件:
private void DisplayPicturebox_MouseMove(object sender, MouseEventArgs e)
{
if (draw)
{
graphics = DisplayPicturebox.CreateGraphics();
SolidBrush MysolidBrush = new SolidBrush(Color.Red);
float newX = (float)DisplayPicturebox.Image.Size.Width / (float)DisplayPicturebox.Size.Width;
float newY = (float)DisplayPicturebox.Image.Size.Height / (float)DisplayPicturebox.Size.Height;
graphics = Graphics.FromImage(DisplayPicturebox.Image);
graphics.FillEllipse(MysolidBrush, e.X * newX, e.Y * newY, Convert.ToInt32(toolStripTextBox1.Text), Convert.ToInt32(toolStripTextBox1.Text));
DisplayPicturebox.Refresh();
}
}
我已经编辑了你的标题。请参阅“”,其中的共识是“不,他们不应该”。