2012-05-25 110 views
0

第一部分:在我的一个项目中,我想在使用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部分后问题

感谢

-Pankaj

+2

不应该'imageContainer.Width'是'controlPosition.right - controlPosition.left'? (和Height一样。) –

+0

谢谢@AdrianMcCarthy。是的,这是我的一个愚蠢的错误。 :( – Pankaj

回答

0

当控件的大小发生变化时,您将有一个WM_SIZE消息发布到您的窗口。您必须根据新尺寸刷新纵横比。

相关问题