在中心绘制图像,同时保持纵横比
Drawing Image in centre while maintaining 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);
但是,当垂直调整控件大小时,图像会向右移动,而不是始终保持在中心位置,同样,当控件水平调整大小时,它会移动到底部。我不知道为什么。我在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 部分
谢谢
-潘卡伊
当控件的大小发生变化时,您将在窗口中发布一条WM_SIZE消息。 您必须根据新大小刷新纵横比。
相关文章:
- 如何在 direct2d 中使用随其窗口重新缩放的效果绘制图像
- 如何在圆圈内绘制图像
- SDL 不绘制图像
- 如何使用QGraphicsItem绘制图像?
- 使用图像指针绘制图像
- 如何在圆角矩形或圆形内部绘制图像
- 在屏幕上绘制图像后背景发生变化
- 在 Allegro5 中绘制图像/字体的一部分
- C++ WinApi 绘制图像.jpg到新窗口
- 无法从 Direct2D png 使用 DirectX9 绘制图像精灵
- 在中心绘制图像,同时保持纵横比
- 如何在MFC对话框的静态区域中绘制图像
- c++在位图上绘制图像并保存
- 在 Direct2D 中绘制图像的一部分
- wxWidgets:定期在wxFrame中重新绘制图像
- 绘制图像的功能
- 在图片控件中绘制图像
- 你如何从矢量<CvPoints>或矢量绘制图像<Point2f>?
- Visual C++如何使用CPaintDC、CDC在CView中重新绘制图像
- OpenGL绘制图像.PIC库