在另一张图片上居中图片

Center image on another image

我对 C# GDI+ 图形还很陌生。

我想在另一个图像上绘制一个图像,该图像应在图像的固定高度和宽度容器中水平和垂直居中。

我试着用水平居中来做到这一点,结果很奇怪。

我正在分享我如何尝试这样做的注释代码,如果有任何更简单的方法,请告诉我,我只想缩放图像并将其居中。

//The parent image resolution is 4143x2330 
//the container for child image is 2957x1456
Image childImage = Image.FromFile(path.Text.Trim());
Image ParentImage = (Image)EC_Automation.Properties.Resources.t1;
Bitmap bmp2 = (Bitmap)ParentImage;
Graphics graphic = Graphics.FromImage(ParentImage); 
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
double posX = (2957 / 2.0d) - (childImage.Width / 2.0d); 
//HAlf of the container size - Half of the image size should make it center in container
graphic.DrawImage((Image)childImage,
new Rectangle(new Point((int)posX, 420), new Size( 2957, 1456))); //Drawing image 

解决了,我画的是固定宽度的图片,本来应该是根据纵横比和新高度调整的新宽度,

我还试图从 Container 中找到图像的中心,它应该是整个父图像的中心

public Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(maxWidth, maxHeight);
    using (var graphics = Graphics.FromImage(newImage))
    {
        // Calculate x and y which center the image
        int y = (maxHeight/2) - newHeight / 2;
        int x = (maxWidth / 2) - newWidth / 2;
        
        // Draw image on x and y with newWidth and newHeight
        graphics.DrawImage(image, x, y, newWidth, newHeight);
    }

    return newImage;
}