开发者

How is the default constructor of System.Drawing.Graphics removed?

开发者 https://www.devze.com 2022-12-31 10:22 出处:网络
When I try to create an object of Graphics, why doesn\'t the following work? System.Drawing.Graphics graphicsObj = new System.Drawing.Graphics();

When I try to create an object of Graphics, why doesn't the following work?

System.Drawing.Graphics graphicsObj = new System.Drawing.Graphics();

(I am aware that I could create a p开发者_如何转开发rivate System.Windows.Forms.Panel Obj; and then do CreateGraphics() if I wanted it to work)

I tried to find a custom constructor for Graphics, but I couldn't find one. Where did Microsoft define it, or how did it block it?


Default constructors are only created by the C# compiler if there are no other declared constructors. In this case it looks like all constructors are internal or private. Basically you don't construct one yourself - you ask for one from an image, control or whatever, or get given one for paint events etc.


It is intuitively obvious that Graphics cannot have a default constructor. You always want what you draw to be visible somewhere. A default constructor could not select the destination of the drawing.

Ways to get a Graphics object:

  • Graphics.FromImage(). You'll draw into a bitmap. Common when resizing images or to create a "canvas".
  • Control.CreateGraphics(). Let's you draw directly to the screen. Always wrong, instead use:
  • Paint event. The e.Graphics argument lets you draw to the screen.
  • PrintPage event. For the PrintDocument class, e.Graphics ends up on a piece of paper.
  • Graphics.FromHdc(). Use in low-level P/Invoke code, draws to a Windows' device context.
  • Graphics.FromHwnd(). As above, draws directly to a native window.

In summary:

  • Draw to the screen with the Paint event
  • Draw to the printer with the PrintPage event
  • Draw to a bitmap with FromImage()


Microsoft did not give the Graphics object constructors. The only way to create an instance is through the static methods, such as CreateGraphics() or FromImage(). That is why your code does not work. Also, as a sidenote, the Graphics object cannot be inherited from.

0

精彩评论

暂无评论...
验证码 换一张
取 消