java – 使图像适合矩形

如果我有一个我知道高度和宽度的图像,那么我怎么能将它放在一个矩形最大的矩形中,而不会拉伸图像.

代码是足够的(但我将在Java中使用).

谢谢.

所以,根据答案,我写道:但是不行.我做错了什么

double imageRatio = bi.getHeight() / bi.getWidth();
double rectRatio = getHeight() / getWidth();
if (imageRatio < rectRatio)
{
    // based on the widths
    double scale = getWidth() / bi.getWidth();
    g.drawImage(bi,(int) (bi.getWidth() * scale),(int) (bi.getHeight() * scale),this);
}
if (rectRatio < imageRatio)
{
    // based on the height
    double scale = getHeight() / bi.getHeight();
    g.drawImage(bi,this);
}

解决方法

确定两者的宽高比(高度除以宽度,例如,高,瘦长矩形具有> 1的长宽比).

如果矩形的宽高比大于图像的长宽比,则会根据宽度(矩形宽度/图像宽度)均匀地缩放图像.

如果矩形的长宽比小于图像的长宽比,则根据高度(矩形高度/图像高度)均匀地缩放图像.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...