c# DrawImage
将图像绘制在指定矩形中央
图像在矩形内居中显示
步骤:
- 设定将要显示的图像大小: private Size imgSize(100, 100);
- 创建一个与ImgSize大小相同的矩形(ImgRect)
- 设定ImgRect的X、Y坐标,将ImgRect位置设定在 大矩形的中央
- 使用Graphics.DrawImage方法绘图,将图像绘制在ImgRect内(DrawImage方法会根据 ImgRect大小自动缩放图片)
实现功能:
将图像显示在Label的中心
效果
private void button1居中绘图_Click(object sender, EventArgs e)
{
//加载图片
Image image = Image.FromFile("C:\\Users\\XXXXXX\\Desktop\\123.gif");
//创建画布
Graphics g = label1.CreateGraphics();
//将图像缩放至100X100大小显示
Size imgSize = new Size(100, 100);
//将图像显示在labeRect中央
Rectangle labeRect = label1.ClientRectangle;
//创建一个与目标显示图像大小相同的矩形
Rectangle imgRect = new Rectangle(0, 0, imgSize.Width, imgSize.Height);
//将imgRect Locatin设定至labeRect的中央
imgRect.X = labeRect.X + (labeRect.Width - imgSize.Width) / 2;
imgRect.Y = labeRect.Y + (labeRect.Height - imgSize.Height) / 2;
g.DrawImage(image, imgRect);
//释放
g.Dispose();
}