c# - 在另一张图片上居中图片

标签 c# winforms gdi+ autoresize

我对 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 

最佳答案

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;
}

关于c# - 在另一张图片上居中图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28632480/

相关文章:

c# - 在 iOS13 上更改状态栏颜色

c# - 引用netcoreapp1.0中的FrameworkAssembly

c# - 在 Release 编译上启用代码

C# TFS workspace.get() 文件已更新

c# - C# .net windows 形式的波斯日期时间选择器

winforms - 绘制渐变矩形的有效方法

c# - Bitmap.Save "Object is currently in use elsewhere"线程问题

C#:用于显示来自 Windows 服务的实时消息的 GUI

c# - 在用户控件单击事件中切换主窗体中的用户控件

.net - 如何从 .NET 中的图标文件中提取特定图像?