How to manually get instance of Graphics object in

2020-02-12 04:29发布

问题:

I know how to work with object of type Graphics (at least I am able to render images) but I always do that by passing graphics object retrieved from OnPaint method.

I would like to display an image when the app is opened (ie in Form_Load method) but have no clue how to obtain the instance of Graphics object I could use? Thanks

回答1:

Using the e.Graphics object that OnPaint() supplies to you is the correct way of doing it. It will run right after the OnLoad() method. The form isn't visible yet in OnLoad.

Getting a Graphics object from Control.CreateGraphics() is supported. However, whatever you draw with this will be wiped out as soon as the form repaints itself. Which happens when the user moves another window across yours (pre-Aero) or when she minimizes and restores or otherwise resizes the window. Use CreateGraphics only ever when animating at a high rate.



回答2:

If you're attempting to create a graphics object from the surface of your form, you can use this.CreateGraphics

If you are attempting to create a new Image, you can always initialize an Image and then call Graphics.CreateGraphics.FromImage(YourImage) e.g.

Bitmap b = new Bitmap(100,100);
var g = Graphics.CreateGraphics.FromImage(b);

At this point, any drawing performed to your Graphics object will be drawn onto your image.



回答3:

None of the preceding answers worked for me. I found Rajnikant Rajwadi solution effective (see https://social.msdn.microsoft.com/Forums/vstudio/en-US/ce90eb80-3faf-4266-b6e3-0082191793f7/creation-of-graphics-object-in-wpf-user-control?forum=wpf)

Here is a horribly condensed call to Graphics.MeasureString(). (please code more responsibly)

SizeF sf = System.Drawing.Graphics.FromHwnd(new System.Windows.Interop.WindowInteropHelper(this).Handle).MeasureString("w", new Font(TheControl.FontFamily.ToString(), (float)TheControl.FontSize));


回答4:

form.CreateGraphics();

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.creategraphics.aspx

http://msdn.microsoft.com/en-us/library/5y289054.aspx



回答5:

And how do you plan to use the Graphics object you got in the Load event?

If you want to paint something on the screen, you have to be in the Paint event, or it will be cleared on the next paint.

What you can do: load another (simple) form, with just a picture, and hide it when your main form is loaded.

Since your Load event will probably run on the UI thread. Call DoEvents to make the other form appear.