C#CreateGraphics方法的三种实现方式

方法一、利用控件或窗体的Paint事件中的PainEventArgs
在窗体或控件的Paint事件中接收对图形对象的引用,作为PaintEventArgs(PaintEventArgs指定绘制控件所用的Graphics)的一部分,在为控件创建绘制代码时,通常会使用此方法来获取对图形对象的引用。
例如:
//窗体的Paint事件的响应方法

代码如下:

private void form1_Paint(object sender, PaintEventArgs e)

{
Graphics g = e.Graphics;
}
也可以直接重载控件或窗体的OnPaint方法,具体代码如下所示:
`
代码如下:
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
}

Paint事件在重绘控件时发生。

方法二、调用某控件或窗体的CreateGraphics方法
调用某控件或窗体的CreateGraphics方法以获取对Graphics对象的引用,该对象表示该控件或窗体的绘图图面。如果想在已存在的窗体或控件上绘图,通常会使用此方法。
例如:
Graphics g = this.CreateGraphics();
方法三、调用Graphics类的FromImage静态方法
由从Image继承的任何对象创建Graphics对象。在需要更改已存在的图像时,通常会使用此方法。
例如:

代码如下:
//名为“g1.jpg”的图片位于当前路径下

Image img = Image.FromFile("g1.jpg");//建立Image对象
Graphics g = Graphics.FromImage(img);//创建Graphics对象

传送门:C#GDI+简单绘图
http://www.cnblogs.com/stg609/archive/2008/03/16/1108333.html

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace DoubleBufferDraw { public partial class DrawLine : Form { class LineObj { private Point m_start; private Point m_end; public LineObj(Point start, Point end) { this.m_start = start; this.m_end = end; } public void Draw(Graphics g, Pen pen) { g.DrawLine(pen, m_start, m_end); } } private Point m_startPoint = Point.Empty; List lineList = new List(); public DrawLine() { InitializeComponent(); } private void drawLine(Graphics graphics, Point startPoint, Point endPoint) { BufferedGraphicsContext context = BufferedGraphicsManager.Current; BufferedGraphics bg = context.Allocate(graphics, this.ClientRectangle); bg.Graphics.Clear(this.BackColor); foreach (LineObj line in this.lineList) { line.Draw(bg.Graphics, SystemPens.ControlText); } bg.Graphics.DrawLine(SystemPens.ControlText, startPoint, endPoint); bg.Render(); bg.Dispose(); bg = null; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); foreach (LineObj line in this.lineList) { line.Draw(e.Graphics, SystemPens.ControlText); } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); this.m_startPoint = new Point(e.X, e.Y); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.Button == MouseButtons.Left) { this.drawLine(this.CreateGraphics(), this.m_startPoint, new Point(e.X, e.Y)); } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); LineObj line = new LineObj(this.m_startPoint, e.Location); this.lineList.Add(line); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值