中心图像在另一个图像C#上

Aze*_*ter 4 c# gdi+ autoresize winforms

嗨,我是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 
Run Code Online (Sandbox Code Playgroud)

Gab*_*ari 7

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;
}
Run Code Online (Sandbox Code Playgroud)


Aze*_*ter -3

解决了这个问题,我正在绘制固定宽度的图像,而它应该根据长宽比和新高度使用新的宽度,

另外,我试图从容器中找到图像的中心,它应该是整个父图像的中心