在中心绘制图像,同时保持纵横比

Drawing Image in centre while maintaining the Aspect Ratio

本文关键字:绘制 图像 在中心      更新时间:2023-10-16

第 1 部分:在我的一个项目中,我想使用 GDI+ 在自定义控件的中心显示图像,同时保持图像的纵横比。这是我的代码

Gdiplus::Image image(imagePathWStr); // imagePathWStr is the Image Path
int originalWidth = image.GetWidth();
int originalHeight = image.GetHeight();
// This code calculates the aspect ratio in which I have to draw the image
int16 cntrlwidth = controlPosition.right - controlPosition.left;  // controlPosition is the custom Control Rect
int16 cntrlheigth = controlPosition.bottom - controlPosition.top;
float percentWidth = (float)cntrlwidth / (float)originalWidth;
float percentHeight = (float)cntrlheigth / (float)originalHeight;
float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
int newImageWidth = (int)(originalWidth * percent);
int newImageHeight = (int)(originalHeight * percent);
Gdiplus::RectF imageContainer;
imageContainer.X = controlPosition.left;
imageContainer.Y = controlPosition.top;
imageContainer.Width = controlPosition.right;
imageContainer.Height = controlPosition.bottom;
Gdiplus::Graphics gdiGraphics(hDC);
Gdiplus::Unit scrUnit = Gdiplus::UnitPixel;
gdiGraphics.DrawImage(&image, imageContainer, 0, 0, originalWidth, originalHeight, scrUnit);
但是,当垂直调整控件大小时,

图像会向右移动,而不是始终保持在中心位置,同样,当控件水平调整大小时,它会移动到底部。我不知道为什么。我在Windows上使用C++。

部分2:现在我也在此上面绘制了一个矩形

Gdiplus::RectF cropRect;
cropRect.X = 100;
cropRect.Y = 100;
cropRect.Width = 300;
cropRect.Height = 300;
Gdiplus::Pen* myPen = new Gdiplus::Pen(Gdiplus::Color::White);
myPen->SetWidth(3);
gdiGraphics.DrawRectangle(myPen, cropRect);

现在,当我调整控件大小时,图像的大小调整正确,但此矩形没有,我相应地将宽度和高度相乘

Gdiplus::RectF cropRectangle;
cropRectangle.X = cropRect.GetLeft();
cropRectangle.Y = cropRec.GetTop();
cropRectangle.Width = (cropRec.Width)* percent;
cropRectangle.Height = (cropRec.Height ) * percent;

我的第 1 部分在 Adrians 回答后已解决,现在我被困在问题的第 2 部分

谢谢

-潘卡伊

当控件的大小发生变化时,您将在窗口中发布一条WM_SIZE消息。 您必须根据新大小刷新纵横比。