C++ 在保持纵横比的同时在中心绘制图像

C++ 在保持纵横比的同时在中心绘制图像,c++,gdi+,C++,Gdi+,第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

第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);
现在,当我调整控件的大小时,图像的大小得到了正确调整,但这个矩形没有,我相应地乘以了宽度和高度

Gdiplus::RectF cropRectangle;
cropRectangle.X = cropRect.GetLeft();
cropRectangle.Y = cropRec.GetTop();
cropRectangle.Width = (cropRec.Width)* percent;
cropRectangle.Height = (cropRec.Height ) * percent;
在阿德里安回答后,我的第一部分已经解决了。现在,我的问题的第二部分被卡住了

谢谢


-Pankaj

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

不应
imageContainer.Width
controlPosition.right-controlPosition.left
?(高度也一样。)谢谢@AdrianMcCarthy。是的,我犯了一个愚蠢的错误(
Gdiplus::RectF cropRectangle;
cropRectangle.X = cropRect.GetLeft();
cropRectangle.Y = cropRec.GetTop();
cropRectangle.Width = (cropRec.Width)* percent;
cropRectangle.Height = (cropRec.Height ) * percent;