Mahlzeit!
Auf einer der Picturebox zeichne ich ein Gitter, das ich als Grafik speichern möchte, um es später ausdrucken zu können.
Beim Speichern bekomme ich je nach Bildformat einen schwarzen Hintergrund oder nichts geliefert.
Was mache ich falsch?
private int _rowCount = 5;
private int _colCount = 3;
private int _cellWidth = 120;
private int _cellHeight = 60;
private string _path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Gitter.png");
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
for (int row = 1; row < _rowCount; row++)
e.Graphics.DrawLine(Pens.Black, 0, row * _cellHeight, _colCount * _cellWidth, row * _cellHeight);
for (int col = 1; col < _colCount; col++)
e.Graphics.DrawLine(Pens.Black, col * _cellWidth, 0, col * _cellWidth, _rowCount * _cellHeight);
e.Graphics.DrawRectangle(Pens.Black, 0, 0, _cellWidth * _colCount, _cellHeight * _rowCount);
}
private void button1_Click(object sender, EventArgs e)
{
using (Graphics g = pictureBox1.CreateGraphics())
{
using (Bitmap b = new Bitmap(pictureBox1.Width, pictureBox1.Height, g))
{
b.Save(_path, System.Drawing.Imaging.ImageFormat.Png);
}
}
}
Hallo und willkommen,
der von dir verwendete Bitmap(Int32, Int32, Graphics)-Konstruktor benutzt nur die DPI-Werte zum Anpassen der Größe - es wird nicht die Grafik selbst kopiert (das ist so technisch gar nicht möglich).
Weise PictureBox.Image
eine Bitmap
zu (es reicht der Bitmap(Int32, Int32)-Konstruktoraufruf) und zeichne dann in diese Bitmap
(mittels der Graphics.FromImage(Image)-Methode).
Danke für den Hinweis 👍
So funktioniert es nun bei mir
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private int _rowCount = 5;
private int _colCount = 3;
private int _cellWidth = 120;
private int _cellHeight = 60;
private string _path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Gitter.png");
private Bitmap _bmp;
public Form1()
{
InitializeComponent();
_bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
}
void DrawCells(Graphics g)
{
for (int row = 1; row < _rowCount; row++)
g.DrawLine(Pens.White, 0, row * _cellHeight, _colCount * _cellWidth, row * _cellHeight);
for (int col = 1; col < _colCount; col++)
g.DrawLine(Pens.White, col * _cellWidth, 0, col * _cellWidth, _rowCount * _cellHeight);
g.DrawRectangle(Pens.White, 0, 0, _cellWidth * _colCount, _cellHeight * _rowCount);
}
void SaveCells(string fileName)
{
using (Graphics g = Graphics.FromImage(_bmp))
{
DrawCells(g);
_bmp.Save(_path, System.Drawing.Imaging.ImageFormat.Png);
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
DrawCells(e.Graphics);
}
private void button1_Click(object sender, EventArgs e)
{
SaveCells(_path);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (_bmp != null)
_bmp.Dispose();
}
}
}