本文已参与「新人创作礼」活动,一起开启掘金创作之路。
//pnlImg(panel) 为容器
//_img(image) 为要绘制显示的图片
private void PaintImgAll(Graphics gph = null)
{
if (_img == null)
return;
bool flag = false;
if (gph == null)
{
gph = pnlImg.CreateGraphics();
// 设置画布的描绘质量
gph.CompositingQuality = CompositingQuality.HighQuality;
gph.SmoothingMode = SmoothingMode.HighQuality;
gph.InterpolationMode = InterpolationMode.HighQualityBicubic;
flag = true;
}
Size szPanel = pnlImg.Size;
Size szPicBox = _img.Size;
//判断 纵横比
float fWidthScale = 1.0f * szPanel.Width / szPicBox.Width;
float fHeightScale = 1.0f * szPanel.Height / szPicBox.Height;
float fMinScale = (fWidthScale > fHeightScale ? fHeightScale : fWidthScale);
//计算新的图片大小
szPicBox = new Size((int)(szPicBox.Width * fMinScale), (int)(szPicBox.Height * fMinScale));
int x = (szPanel.Width - szPicBox.Width) / 2;
int y = (szPanel.Height - szPicBox.Height) / 2;
//可以显示到pictureBox1控件上
//pictureBox1.Size = szPicBox;
//pictureBox1.Location = new Point((szPanel.Width - szPicBox.Width) / 2, (szPanel.Height - szPicBox.Height) / 2);
//绘制的新矩形
Rectangle rectNew = new Rectangle(x, y, szPicBox.Width, szPicBox.Height);
//绘制原图片指定大小
Rectangle rect =new Rectangle(0, 0, _img.Width, _img.Height)
gph.DrawImage(_img, rectNew, rect, GraphicsUnit.Pixel);
//创建Graphics对象——直接绘制,容器多大照片就多大
//RectangleF rect = new RectangleF(0, 0, pnlCards.Width, pnlCards.Height);
//gph.DrawImage(_img, rect, new Rectangle((szPanel.Width - szPicBox.Width) / 2, (szPanel.Height - szPicBox.Height) / 2, _img.Width, _img.Height), GraphicsUnit.Pixel);
//gph.DrawImage(_img, rect, new Rectangle(0, 0, width, height), GraphicsUnit.Pixel);
//gph.DrawImage(_img,x , y, _img.Width, _img.Height);
if (flag)
{
//释放内存
gph.Dispose();
}
}