代码
//使用PaintEventArgs 参数创建Graphics对象
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(new SolidBrush(Color.Red), 10, 20, 13, 7);
}
private void button1_Click(object sender, EventArgs e)
{
Graphics graph;
//使用窗口句柄创建Graphics
graph = Graphics.FromHwnd(this.Handle);
graph.FillRectangle(new SolidBrush(Color.Blue), 30, 20, 13, 7);
//使用控件句柄创建Graphics
graph = Graphics.FromHwnd(this.pictureBox1.Handle);
graph.FillRectangle(new SolidBrush(Color.Red ), 30, 20, 13, 7);
//创建梯度
System.Drawing.Drawing2D.LinearGradientBrush lineGrBrush;
graph = Graphics.FromHwnd(this.Handle);
lineGrBrush = new System.Drawing.Drawing2D.LinearGradientBrush(
new Point(10, 30),
new Point(30, 40),
Color.FromArgb(255, 255, 0, 0),
Color.FromArgb (255,0,0,255));
graph.FillRectangle(lineGrBrush, 10, 30, 20, 10);
//路径梯度
Rectangle rectSquare;
System.Drawing.Drawing2D.GraphicsPath graphPath;
System.Drawing.Drawing2D.PathGradientBrush brushSquare;
graph = Graphics.FromHwnd(this.Handle);
graphPath = new System.Drawing.Drawing2D.GraphicsPath();
rectSquare = new Rectangle(50, 20, 23, 27);
graphPath.AddRectangle(rectSquare);
brushSquare = new System.Drawing.Drawing2D.PathGradientBrush(graphPath);
brushSquare.CenterColor = Color.FromArgb(255, 0, 255, 0);
brushSquare.SurroundColors = new Color[] { Color.FromArgb(255, 0, 0, 255) };
graph.FillRectangle(brushSquare, rectSquare);
//一定要注意释放资源....
graph.Dispose();
}