Reputation: 531
My goal is to crop an image while keeping the aspect ratio 16:9 without losing parts of the original image by putting the original image in the center depending on current ratio.
My crop-size is breiteNeu
for width of the image to be cropped and hoeheNeu
for height of the image to be cropped. xNeu
is the x-coordinate of the image to be cropped and yNeu
is the y-coordinate of the image to be cropped.
This is my code
if (breiteNeu > hoeheNeu)
{
if (breiteNeu / hoeheNeu > 1.777)
{
Console.WriteLine("1");
float hj = 0.5625f * breiteNeu;
yNeu -= (int)((hj - hoeheNeu) / 2);
hoeheNeu = (int)hj;
}
else
{
Console.WriteLine("2");
float bj = 1.777f * hoeheNeu;
xNeu -= (int)((bj - breiteNeu) / 2);
breiteNeu = (int)bj;
}
}
else
{
if (breiteNeu / hoeheNeu > 0.5625)
{
Console.WriteLine("3");
float hj = 1.777f * breiteNeu;
yNeu -= (int)((hj - hoeheNeu) / 2);
hoeheNeu = (int)hj;
}
else
{
Console.WriteLine("4");
float bj = 0.5625f * hoeheNeu;
xNeu -= (int)((bj - breiteNeu) / 2);
breiteNeu = (int)bj;
}
}
1 to 3 ( Console.WriteLine("1")
to Console.WriteLine("3")
) seem to work, but 4 always crops out parts of the image by reducing the width to keep the aspect ratio.
How do I need to change especially 4 to keep the aspect ratio yet contain the whole breiteNeu
and hoeheNeu
(the original ones before hoeheNeu = hj
resp. breiteNeu = bj
were assigned) area?
Upvotes: 0
Views: 215
Reputation: 539
In C#, division between integers always results in an integer. If both breiteNeu and hoeheNeu are integers, that may be causing the unexpected results.
Cast one of them to float to compare them properly to the float in your if statements.
if (breiteNeu / (float)hoeheNeu > 1.777)
and
if (breiteNeu / (float)hoeheNeu > 0.5625)
The math looks correct.
Upvotes: 1