从 BufferedGraphics C# 制作位图
Making Bitmap from BufferedGraphics C#
我在 C# WinForms 中制作了一个简单的程序,类似于 MSPaint。我目前卡住的一件事是我想从我正在绘制的 BufferedGraphics 制作 Bitmap 然后保存它。但是当我保存的时候,文件里什么也没有,只有一张空白的图片。
代码如下:
private BufferedGraphics picture;
public Form1()
{
InitializeComponent();
picture = BufferedGraphicsManager.Current.Allocate(MainPanel.CreateGraphics(), MainPanel.DisplayRectangle);
picture.Graphics.FillRectangle(Brushes.White, MainPanel.DisplayRectangle);
picture.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
picture.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
}
private void Draw()
{
if (mouseDown)
{
Point cursorPos = MainPanel.PointToClient(Cursor.Position);
picture.Graphics.FillEllipse(selectedColor, cursorPos.X - slider.Value / 2, cursorPos.Y - slider.Value / 2, slider.Value, slider.Value);
picture.Render();
}
}
private void Save()
{
Bitmap result = new Bitmap(MainPanel.Width, MainPanel.Height, picture.Graphics);
result.Save("image.png", System.Drawing.Imaging.ImageFormat.Png);
}
检查下面的代码片段;
BufferedGraphics buffer;
int bufferWidth, bufferHeight;
using (Bitmap bitmap = new Bitmap(bufferWidth, bufferHeight))
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
buffer.Render(graphics);
}
bitmap.Save("a.png", ImageFormat.Png);
}
我在 C# WinForms 中制作了一个简单的程序,类似于 MSPaint。我目前卡住的一件事是我想从我正在绘制的 BufferedGraphics 制作 Bitmap 然后保存它。但是当我保存的时候,文件里什么也没有,只有一张空白的图片。
代码如下:
private BufferedGraphics picture;
public Form1()
{
InitializeComponent();
picture = BufferedGraphicsManager.Current.Allocate(MainPanel.CreateGraphics(), MainPanel.DisplayRectangle);
picture.Graphics.FillRectangle(Brushes.White, MainPanel.DisplayRectangle);
picture.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
picture.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
}
private void Draw()
{
if (mouseDown)
{
Point cursorPos = MainPanel.PointToClient(Cursor.Position);
picture.Graphics.FillEllipse(selectedColor, cursorPos.X - slider.Value / 2, cursorPos.Y - slider.Value / 2, slider.Value, slider.Value);
picture.Render();
}
}
private void Save()
{
Bitmap result = new Bitmap(MainPanel.Width, MainPanel.Height, picture.Graphics);
result.Save("image.png", System.Drawing.Imaging.ImageFormat.Png);
}
检查下面的代码片段;
BufferedGraphics buffer;
int bufferWidth, bufferHeight;
using (Bitmap bitmap = new Bitmap(bufferWidth, bufferHeight))
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
buffer.Render(graphics);
}
bitmap.Save("a.png", ImageFormat.Png);
}