在Form1中添加变量:
private
Image smallImage;
修改:
public
Form1()
... {
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
smallImage = new Bitmap("C:\1.jpg");
}
/**/ /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
... {
if( disposing )
...{
smallImage.Dispose();
if (components != null)
...{
components.Dispose();
}
}
base.Dispose( disposing );
}
... {
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
smallImage = new Bitmap("C:\1.jpg");
}
/**/ /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
... {
if( disposing )
...{
smallImage.Dispose();
if (components != null)
...{
components.Dispose();
}
}
base.Dispose( disposing );
}
添加自定义函数:
private
void
MyDraw(Graphics e)
... {
Graphics g = e;
g.FillRectangle(Brushes.Black, ClientRectangle);
Brush tBrush = new TextureBrush(smallImage, new Rectangle(0, 0, smallImage.Width, smallImage.Height));
Font tFont = new Font("方正粗倩繁体", 48, FontStyle.Bold|FontStyle.Italic);
g.DrawString("我的第一个C#版GDI+程序!", tFont, tBrush, ClientRectangle);
tBrush.Dispose();
tFont.Dispose();
}
... {
Graphics g = e;
g.FillRectangle(Brushes.Black, ClientRectangle);
Brush tBrush = new TextureBrush(smallImage, new Rectangle(0, 0, smallImage.Width, smallImage.Height));
Font tFont = new Font("方正粗倩繁体", 48, FontStyle.Bold|FontStyle.Italic);
g.DrawString("我的第一个C#版GDI+程序!", tFont, tBrush, ClientRectangle);
tBrush.Dispose();
tFont.Dispose();
}
最后调用:
private
void
button1_Click(
object
sender, System.EventArgs e)
... {
Graphics g = this.CreateGraphics();
MyDraw(g);
g.Dispose();
}
private void Form1_Paint( object sender, System.Windows.Forms.PaintEventArgs e)
... {
MyDraw(e.Graphics);
}
... {
Graphics g = this.CreateGraphics();
MyDraw(g);
g.Dispose();
}
private void Form1_Paint( object sender, System.Windows.Forms.PaintEventArgs e)
... {
MyDraw(e.Graphics);
}
根据MSDN:
创建 Graphics 对象
图形对象可以用各种方法来创建:
- 接收对图形对象的引用,该对象为窗体或控件的 <?XML:NAMESPACE PREFIX = MSHelp NS = "http://msdn.microsoft.com/mshelp" /> 事件中 的一部分。在为控件创建绘制代码时,通常会使用此方法来获取对图形对象的引用。
- 调用某控件或窗体的 方法来获取对 Graphics 对象的引用,该对象表示该控件或窗体的绘图表面。如果想在已存在的窗体或控件上绘图,则可使用此方法。
- 从继承自的任何对象创建 Graphics 对象。此方法在您需要更改已存在的图像时十分有用。
以上实现了前两种方式。
忘了家效果图:
c盘下那个1.jpg: