开发者

Scale image to fixed-size canvas in .NET

I have a fixed-size canvas (e.g. presentation slide). Need to embed a picture into it without any quality distortion. If the image is smaller than the canvas, it must be centered. If it's larger, it has to be开发者_如何学运维 scaled down to fit.

Does any reliable algorithm exist or I have to create it from scratch?


The scaling you need is simply

scale = desired size / actual size

To avoid distortion you apply the same scale to both the height and width.

To ensure you get the right size you find the longest dimension and scale using that so your code becomes:

if (height > width)
{
    scale = desiredHeight / actualHeight;
}
else
{
    scale = desiredWidth / actualWidth;
}

Make sure you've converted the height and width to double values to avoid integer arithmetic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜