简体   繁体   中英

C# painting Graphics on Bitmap dynamically dillema

Ok, so, first of all, I have a list of data (multiple rows). That data needs to be drawn on a Bitmap for preview (the Bitmap being a diploma). After clicking the preview button, I will be sent to another tab where I can preview the job (the Bitmap with Graphics on it). After this, the user can choose to print the data (the Graphics).

The Graphics have to change if I select a different row.

The thing is: I don't know how should I implement the Bitmap, where and when to draw it over the pictureBox. I've tried a number of methods (having a single static Bitmap where I draw every time - fails because cannot clear it for a second redraw, having a method for generating the Bitmap - fails because of a memory leak), but I either end up only with the text, only with the background image or either with a huge memory leak (because I need to show the drawn strings, I cannot dispose the Bitmap).

Do you have any suggestions on how should I approach this?

Selecting the row for which we're generating the preview

The way the preview window should look like (with text on it, obviously)

Well you need either two Bitmaps, one to use for overdrawing and one as the source or you need to create the result dynamically each time.

In any case you need to

  • keep the original graphics ready
  • dispose of the combination when done with it

I suggest to keep things simple and create a result image upon SelectionChanged :

Bitmap diplomaBackground = null;  // load upon startup
Bitmap result = null;

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    if (result != null)
    {
        if (pb_preview.Image != null) pb_preview.Image = null;
        result.Dispose();
    }

    if (dataGridView1.SelectedRows.Count > 0)
    {
        result = CreateNewDiploma(dataGridView1.SelectedRows[0].Index);
        pb_preview.Image = result;
    }
}

Bitmap CreateNewDiploma(int rowIndex)
{
    Bitmap bmp = new Bitmap(diplomaBackground);

    using (Graphics G = Graphics.FromImage(bmp))
    {
        // draw the data..
    }
    return bmp;
}

Set the preview box to zoom.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM