将动态宽度高度矩形居中放置在恒定大小的正方形中

时间:2013-10-02 07:12:29

标签: c# bitmap system.drawing

我从文件夹中获取图像并将其绘制在白色的btimap上,如下面的代码所示

Image newImage = new Bitmap(whitesize, whitesize);
using (Graphics graphicsHandle = Graphics.FromImage(newImage))
{
    graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphicsHandle.FillRectangle(System.Drawing.Brushes.White,0,0,whiteHeight,whiteHeight);
    graphicsHandle.CompositingMode = CompositingMode.SourceOver;
    graphicsHandle.DrawImage(image, whiteHeight, 0, newWidth, newHeight);             
}

whiteHeight是方形宽度和高度

将whiteHeight除以2将不起作用,因为newWidthnewHeight是动态的,更多的是数学问题

1 个答案:

答案 0 :(得分:1)

您实际上需要找到容器的中心和您需要放置的图像的中心,然后使它们相同。

容器的中心是:

(X,Y) = (ContainerWidth/2,ContainerHeight/2) = (whiteHeight/2,whiteHeight/2)

因为whitesize是常数,所以中心也是常数,并且其坐标已知。

现在你需要找到一个方程来使图像居中。

您需要再次找到图像的动态中心

(Xi,Yi) = (newWidth /2,newHeight /2)

这当然是动态的。 现在,您需要从顶部和左侧找到边距以放置图像。

左边距将被称为ImageLeft,而Top将被称为ImageTop。

现在您可能已经了解ImageLeft将在图像中心的左侧稍微多一点,该位将等于

ImageLeft = CenterX - (newWidth / 2)

CenterX被称为必须等于容器的中心,所以:

ImageLeft = (whiteHeight/ 2) - (newWidth / 2)

ContainerWidth是一个已知的常量和ImageWidth,虽然是动态的,但它会在运行时知道,因为它将由图像属性提供。

所以,现在你已经用已知因素表达了图像的左点。

以同样的方式你可以发现ImageTop等于:

ImageTop = (whiteHeight/ 2) - (newHeight / 2)

现在您知道从哪里开始绘制图像的确切位置,即:

graphicsHandle.DrawImage
(
    image, 
    (whiteHeight/ 2) - (newWidth / 2), 
    (whiteHeight/ 2) - (newHeight / 2), 
    newWidth, 
    newHeight
);
相关问题