C#Graphics

转自:http://listsetio090529.blog.163.com/blog/static/1327321842010479331240/

所有通过GDI+绘制的工作都会涉及到Graphics对象,下面列举几种使用到它的场景:
1. 在绘制过程中,Windows Form控件会通过OnPaint和OnPaintBackground方法传递PaintEventArgs参数,而Graphics对象就包括在其中;
2. 同样,该参数也被OnPaint事件引发的其它Paint事件所传递和处理;
3. 打印的时候,PrintPage事件提供了PrintPageEventArgs参数,它也包括了操作打印机的Graphics对象,你可以直接操作这个对象绘制各种图形,它们会和显示在屏幕上一样被打印出来。

获得Graphics对象

当你写绘图程序的时候,你可以处理被封装在PaintEventArgs对象中的Graphics对象。这里有两种方法来控制Graphics对象。你可以重写保护类型的OnPaint或OnPaintBackground方法,或者,添加一个Paint事件句柄。在所有的这些场景中,Graphics对象都是包含在PaintEventArgs对象中传递。

下面显示不同的方法:

protected override void OnPaint(PaintEventArgs e)
     {
      //get the Graphics object from the PaintEventArgs
       Graphics g=e.Graphics;
       g.DrawLine(....);

      //or use it directly
       e.Graphics.DrawLine(....);
       
      //Remember to call the base class or the Paint event won't fire
      base.OnPaint (e);
     }
    //This is the Paint event handler
    private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
     {
      //get the Graphics object from the PaintEventArgs
       Graphics g=e.Graphics;
       g.DrawLine(....);

      //or use it directly
       e.Graphics.DrawLine(....);
     }


从上面的代码,可以看出来,你可以得到一个Graphics对象的引用,或者直接从PaintEventArgs中使用。

记住:千万别在这些方法的范围之外保存Graphics对象。

用它来做什么?

当你的程序已经得到Graphics对象后,你可以做以下几类事情,它们分成5类:

绘制图形(Stroke a shape): 例如使用画笔Pen对象绘制矩形、椭圆和线条。Pen对象有不同的线条宽度、颜色及其它许多属性,我们会在接下来的其它文章中细说。

填充图形(Fill a shape): 已经绘制出的图形,可以使用画刷Brush对象填充颜色。在GDI+中,Brush有许多复杂的设置,不过基本都是使用颜色填充一个面积。

绘制文本(Draw a string): 文本可以通过使用DrawString方法显示放置到Graphics的上面。

绘制图像(Draw an image): Image可以通过DrawImage方法以任何比例绘制。

修改Graphics对象(Modify the Graphics object): 有许多方法用于改变Graphics对象的效果。你可以在牺牲速度的基础上,提升图像的质量。你还可以改变Graphics的输出,做出一些旋转、缩放或扭曲等效果。

图1 绘制及填充图形

protected  override void OnPaint(PaintEventArgs e)
     {
      //Get the Graphics object
       Graphics g=e.Graphics;
       //Draw a line
       g.DrawLine(Pens.Red,10,5,110,15);
        //Draw an ellipse
       g.DrawEllipse(Pens.Blue,10,20,110,45);
        //Draw a rectangle
       g.DrawRectangle(Pens.Green,10,70,110,45);
        //Fill an ellipse
       g.FillEllipse(Brushes.Blue,130,20,110,45);
        //Fill a rectangle
       g.FillRectangle(Brushes.Green,130,70,110,45);
      base.OnPaint (e);

     }


注意点:

总的来说,你必须记着只能使用系统传递给你的Graphics对象。

GDI+ is an "Immediate Mode" system. This is to say that the Graphics object has no knowledge of objects, only areas of colour. Shapes and lines are only remembered until they are painted over by a different colour.

你不可以在上面那些方法的作用范围之外使用Graphics对象,因为,它会在下次使用之前被销毁Destroy

原文地址:https://www.cnblogs.com/panweishadow/p/2865119.html