【发布时间】:2012-05-26 06:01:29
【问题描述】:
第 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;
在 Adrians 回答之后我的第 1 部分已经解决,现在我被困在我的问题的第 2 部分
谢谢
-潘卡杰
【问题讨论】:
-
不应该
imageContainer.Width是controlPosition.right - controlPosition.left吗? (对于身高也是如此。) -
谢谢@AdrianMcCarthy。是的,这对我来说是一个愚蠢的错误。 :(