C# 保存面板图像会得到不同的结果
下面是将面板信息更改为位图的代码。 位图首先由我的面板信息生成,然后保存为图像文件。 我确认宽度、高度和边界表示我的面板提供的正确信息。 我目前不确定为什么我的结果bmp/jpeg文件与面板上的图像不同 //位图保存功能C# 保存面板图像会得到不同的结果,c#,C#,下面是将面板信息更改为位图的代码。 位图首先由我的面板信息生成,然后保存为图像文件。 我确认宽度、高度和边界表示我的面板提供的正确信息。 我目前不确定为什么我的结果bmp/jpeg文件与面板上的图像不同 //位图保存功能 Bitmap bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height); Debug.WriteLine("bounds: " + panel1.ClientRecta
Bitmap bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
Debug.WriteLine("bounds: " + panel1.ClientRectangle);
this.panel1.DrawToBitmap(bmp, panel1.ClientRectangle);
bmp.Save(@"C:\Documents and Settings\Flaw\Desktop\Test.bmp", ImageFormat.Bmp);
System.Drawing.Graphics graphicsObj;
graphicsObj = this.panel1.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Black, 5);
graphicsObj.Clear(Color.White);
//graphicsObj.DrawLine(myPen, 50, 50, 100, 100);
if (bCircle)
{
graphicsObj.DrawEllipse(myPen, x, y, 100, 100);
}
else if (bSquare)
{
graphicsObj.DrawRectangle(myPen, x, y, 100, 100);
}
//绘图功能
Bitmap bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
Debug.WriteLine("bounds: " + panel1.ClientRectangle);
this.panel1.DrawToBitmap(bmp, panel1.ClientRectangle);
bmp.Save(@"C:\Documents and Settings\Flaw\Desktop\Test.bmp", ImageFormat.Bmp);
System.Drawing.Graphics graphicsObj;
graphicsObj = this.panel1.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Black, 5);
graphicsObj.Clear(Color.White);
//graphicsObj.DrawLine(myPen, 50, 50, 100, 100);
if (bCircle)
{
graphicsObj.DrawEllipse(myPen, x, y, 100, 100);
}
else if (bSquare)
{
graphicsObj.DrawRectangle(myPen, x, y, 100, 100);
}
通过保存位图得到的结果
我的面板1上的图像(从我的窗口窗体裁剪)
您的Bounds属性是面板与父容器的关系,因此这并不总是有效:
this.panel1.DrawToBitmap(bmp, panel1.Bounds);
请尝试以下方法:
this.panel1.DrawToBitmap(bmp, panel1.ClientRectangle);
位图大小还应使用ClientSize属性,因为面板的宽度和高度属性包括任何边框大小:
Bitmap bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
根据您的更新,CreateGraphics是一个临时画布,不会成为面板的一部分,因此没有要保存的内容。改为使用面板的绘制事件:
private void panel1_Paint(object sender, PaintEventArgs e) {
using (Pen myPen = new Pen(Color.Black, 5)) {
e.Graphics.Clear(Color.White);
if (bCircle) {
e.Graphics.DrawEllipse(myPen, x, y, 100, 100);
} else if (bSquare) {
e.Graphics.DrawRectangle(myPen, x, y, 100, 100);
}
}
}
要进行更新,只需使控件无效:
panel1.Invalidate();
我将代码更新为:Bitmap bmp=新位图(panel1.ClientSize.Width,panel1.ClientSize.Height);Debug.WriteLine(“边界:+panel1.ClientRectangle”);这个.panel1.DrawToBitmap(bmp,panel1.ClientRectangle);保存(@“C:\Documents and Settings\Defect\Desktop\Test.bmp”,ImageFormat.bmp);但现在的结果是一个纯色灰色,与windows窗体颜色相同。@user3235731我不知道您的面板中有什么。您需要记录这些内容。@user3235731您对帖子的编辑没有帮助。你在画板上画画吗?他们的控件是否在面板中?那个面板怎么会有黑色边框的?这是可以猜到的。告诉他先最小化并恢复窗口:)@HansPassant CreateGraphics,通常的嫌疑犯。