您好我是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
答案 0 :(得分: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;
}
答案 1 :(得分:-1)
解决了它,我正在绘制固定宽度的图像,而它应该是基于宽高比和新高度的新宽度,
此外,我正在尝试从Container中找到图像的中心,这应该是整个父图像的中心