سؤال

i get an image from a folder and draw it over a white btimap as in the following code

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 is the square width and height

dividing whiteHeight by 2 wont work, because newWidth and newHeight are dynamic, ts more of a math question

هل كانت مفيدة؟

المحلول

You actually need to find the center of the container and the center of the image you need to place in and then make them the same.

Th center of the container would be:

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

since whitesize is a constant then the center is a constant too and its coordinates known.

Now you need to find an equation to get the image centered.

Again you will need to find the dynamic center of the image which again will be

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

This is dynamic of course. Now you need to find the margins from Top and Left in order to place the image.

The Left Margin will be called ImageLeft and the Top will be called ImageTop.

Now as you may understand the ImageLeft will be a bit more to the left of the center of the image, and that bit will equal to

ImageLeft = CenterX - (newWidth / 2)

CenterX is known as it must be equal to the center of the container, so:

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

ContainerWidth is a known constant and ImageWidth, though dynamic, it will be known at run time, as it will be provided by the image properties.

So, now you have the Left point of the Image expressed by known factors.

In the same way you can find that the ImageTop equals:

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

Now you know the exact point of where to start drawing your image, and that is:

graphicsHandle.DrawImage
(
    image, 
    (whiteHeight/ 2) - (newWidth / 2), 
    (whiteHeight/ 2) - (newHeight / 2), 
    newWidth, 
    newHeight
);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top