现在的位置: 首页 > 综合 > 正文

如何获取Graphics对象

2012年06月27日 ⁄ 综合 ⁄ 共 1496字 ⁄ 字号 评论关闭
在.NET中,可以通过以下方法获取Graphics对象。
1. 从Paint事件的参数中获取。
窗体和许多控件都有一个Paint事件,有一个PaintEventArgs类型的参数e。
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        
{
            
//获取Graphic对象
            Graphics g = e.Graphics;
            
//书写绘图代码
            g.DrawRectangle(Pens.Red,10,10,100,50);
            
//释放Graphic对象占用的资源
            g.Dispose();

        }

窗体的Paint事件是最常用于放置绘图代码的地方,每当窗体被其他窗体挡住,再次显示的时候,窗体的所有内容必须被重绘,否则会得到一个空白的窗体。

2. 用CreateGraphics方法创建。
如果需要在Paint方法以外绘图,可以通过控件或窗体的CreateGraphics方法来获取Graphics对象。

private void button1_Click(object sender, System.EventArgs e)
        
{
            Graphics g 
= button1.CreateGraphics();
            
//画一个椭圆
            g.DrawEllipse(Pens.Red,5,5,button1.Width-10,button1.Height-10);
            g.Dispose();
        }

3. 对Image对象调用Graphics.FromImage获取。

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        
{
            
//创建Image对象
            Bitmap image1 = new Bitmap("football.jpg");
            
//窗体的绘图对象
            Graphics formE = e.Graphics;
            
//图像的绘图对象
            Graphics imageE = Graphics.FromImage(image1);
            
//将第二幅图覆盖到第一幅的左上角
            imageE.DrawImage(new Bitmap("asdf.JPG"),new Rectangle(0,0,this.ClientSize.Width/2,this.ClientSize.Height/2));
            
//将合成好的图像绘制在窗体上
            formE.DrawImage(image1,new Rectangle(0,0,this.ClientSize.Width,this.ClientSize.Height));

            
//释放所有资源
            formE.Dispose();
            imageE.Dispose();
            image1.Dispose();
        }

抱歉!评论已关闭.