[英]How can I get a convert a Graphics object to a Bitmap (or access it as a Bitmap)
[英]How can I save a graphics object to a bitmap in a "paint" winforms application?
我的問題是:當我嘗試將圖形 object 保存到 bitmap 圖像時,它沒有正確保存,而是圖像是黑色的,文件中沒有其他內容。
我看過其他答案,但我認為在圖形object中多次繪制時會有所不同。
所以,這是我的嘗試,請讓我知道我的問題出在哪里。
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace PenFlip
{
public partial class Match : Form
{
Graphics g;
private int x = -1;
private int y = -1;
private bool moving;
private Pen pen;
private Bitmap testBmp;
public Match()
{
InitializeComponent();
g = panel1.CreateGraphics();
g.SmoothingMode = SmoothingMode.AntiAlias;
pen = new Pen(Color.Black, 5);
pen.StartCap = pen.EndCap = LineCap.Round;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
PictureBox pictureBox = (PictureBox) sender;
pen.Color = pictureBox.BackColor;
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
moving = true;
x = e.X;
y = e.Y;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (moving && x != -1 && y != -1)
{
g.DrawLine(pen, new Point(x, y), e.Location);
x = e.X;
y = e.Y;
}
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
moving = false;
x = -1;
y = -1;
g.Save();
}
private void button1_Click(object sender, EventArgs e)
{
// prints out the black image
testBmp = new Bitmap(400, 200, g);
testBmp.Save(@"test.bmp", ImageFormat.Bmp);
}
}
}
呃, Bitmap
的使用很棘手並且有很多陷阱(這就是為什么不推薦使用它,順便說一句)。 嘗試從內存中的 bitmap 創建圖形 object,而不是從控件中獲取它。 bitmap 應該是主要的 object,而不是Graphics
實例。 你不知道控件對你的 bitmap 做了什么。
所以在構造函數中,做類似的事情:
public Match()
{
InitializeComponent();
bitmap = new Bitmap(panel1.Width, panel1.Height, PixelFormat.Format32bppArgb);
pen = new Pen(Color.Black, 5);
pen.StartCap = pen.EndCap = LineCap.Round;
}
在每個 function 中,從 bitmap 創建一個圖形 object:
using (var graphics = Graphics.FromImage(image))
{
graphics.Draw(...);
}
您現在需要手動更新面板,例如通過附加到它的 OnPaint 事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.