How to manually get instance of Graphics object in WinForms?

前端 未结 5 1097
萌比男神i
萌比男神i 2020-12-19 01:50

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.

相关标签:
5条回答
  • 2020-12-19 02:22

    form.CreateGraphics();

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

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

    0 讨论(0)
  • 2020-12-19 02:22

    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.

    0 讨论(0)
  • 2020-12-19 02:23

    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.

    0 讨论(0)
  • 2020-12-19 02:37

    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.

    0 讨论(0)
  • 2020-12-19 02:40

    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));
    
    0 讨论(0)
提交回复
热议问题