2012-05-25 113 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消息發佈到您的窗口。您必須根據新尺寸刷新縱橫比。

相關問題