在GDI+中绘制和克隆图像
在GDI+中绘制和克隆图像
1.绘制图像
在绘制图像时,可以使用Bitmap类对象指定Image图像,然后调用Graphics类中的DrawImage方法进行绘制。DrawImage方法为可重载方法,它主要用来在指定位置绘制指定的Image图像,其常用格式有以下3种。
(1)在指定的位置按原始大小绘制指定的Image图像。
语法:
public void DrawImage (
Image image,
Point point)
参数说明如下。
image:要绘制的Image图像。
point:Point结构,它表示所绘制图像的左上角的位置。
(2)在指定位置按指定大小绘制指定的Image图像。
语法:
public void DrawImage (
Image image,
Rectangle rect)
参数说明如下。
image:要绘制的Image图像。
rect:Rectangle结构,它指定所绘制图像的位置和大小。
(3)在指定位置按指定大小绘制指定Image图像的指定部分。
语法:
public void DrawImage (
Image image,
Point[] destPoints,
Rectangle srcRect,
GraphicsUnit srcUnit)
DrawImage方法中各参数及说明如表1所示。

表1 DrawImage方法各参数及说明
示例
绘制图像
本示例中,当程序运行时,单击【绘制图像】按钮,在窗体中的指定位置根据已创建的Bitmap对象绘制一幅指定大小的图像。示例运行结果如图1所示。

图1 绘制图像
Form1窗体中,在【绘制图像】按钮的Click事件中分别声明Graphics类和Bitmap类的两个实例对象,然后调用Graphics对象的DrawImage方法,在窗体中根据已创建的Bitmap对象绘制一幅指定大小的图像。【绘制图像】按钮的Click事件代码如下:
private void button1_Click(object sender, EventArgs e)
{
Graphics graphics = this.CreateGraphics();
Bitmap bitmap = new Bitmap("image.jpg");
graphics.DrawImage(bitmap, 20, 20, 180, 130);
}
完整程序代码如下:
★ ★★★★Form1.cs窗体代码文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace _6_17
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Graphics graphics = this.CreateGraphics();
Bitmap bitmap = new Bitmap("image.jpg");
graphics.DrawImage(bitmap, 20, 20, 180, 130);
}
}
}
★ ★★★★Form1.Designer.cs窗体设计文件完整程序代码★★★★★
namespace _6_17
{
partial class Form1
{
///
/// 必需的设计器变量。
///
private System.ComponentModel.IContainer components = null;
///
/// 清理所有正在使用的资源。
///
/// 如果应释放托管资源,为 true;否则为 false。
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
///
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
///
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(65, 155);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "绘制图像";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(222, 189);