简体   繁体   中英

How to determine that Drawing.Graphics object is related to given Bitmap object?

I have a array of Bitmaps and a array of Graphics. Initially each Bitmap object have our corresponding Graphics object in these arrays. But during the work bitmaps in array may be replaced by new instances or change their positions in array. So I need a way to find proper Graphics object that corresponding to given Bitmap object (or to make sure that is no corresponding Graphics object in graphics-array).

please look this example code in C#:

void Main()
{
   // make some bitmaps
   Bitmap b1 = new Bitmap(100,100);
   Bitmap b2 = new Bitmap(100,100);

   // make graphics of our bitmaps
   Graphics g1 = Graphics.FromImage(b1);
   Graphics g2 = Graphics.FromImage(b2);

   bool result = Test(b1, g2);
}

bool Test(Bitmap b, Graphics g)
{
   // how can I check that given "g" is really created from given "b"?
   // ???
}

If the graphics are being created in a central place you could maintain a lookup table using a dictionary, Dictionary<Bitmap, Graphics> .

Alternatively, you could also use the Tag property of the Bitmap to store a reference to the Graphics object.

   Bitmap b1 = new Bitmap(100,100); 
   Bitmap b2 = new Bitmap(100,100); 

   // make graphics of our bitmaps 
   Graphics g1 = Graphics.FromImage(b1); 
   Graphics g2 = Graphics.FromImage(b2); 

   // Track the graphics object for each bitmaps
   // NOTE: be sure to dispose the Graphics when you're done with the Bitmap.
   b1.Tag = g1;
   b2.Tag = g2;

In any case, make sure you are properly disposing of your Graphics objects once you no longer need them.

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