【问题标题】:Drawing Image in centre while maintaining the Aspect Ratio在保持纵横比的同时在中心绘制图像
【发布时间】: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.WidthcontrolPosition.right - controlPosition.left 吗? (对于身高也是如此。)
  • 谢谢@AdrianMcCarthy。是的,这对我来说是一个愚蠢的错误。 :(

标签: c++ gdi+


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    相关资源
    最近更新 更多