我正在尝试通过保持纵横比来调整图像大小。 它应该足够大,可以填充屏幕,没有空白区域,如果需要,一些图像应该在屏幕外。
下图显示了如何根据黑屏尺寸调整黄色图像的大小。
下面是我实际使用的代码,有没有更好的方法来做到这一点?
if(bwidth > bheight) {
if(bwidth > swidth && bheight > sheight) {
new_height = sheight;
new_width = (int) ((double) (bwidth/100)*(sheight/((double) (bheight)/100)));
} else if(bwidth > swidth && bheight < sheight) {
new_height = sheight;
new_width = (int) ((double) (bwidth/100)*(sheight/((double) (bheight)/100)));
} else if(bwidth < swidth && bheight < sheight) {
new_height = sheight;
new_width = (int) ((double) (bwidth/100)*(sheight/((double) (bheight)/100)));
} else if(bwidth < swidth && bheight > sheight) {
new_height = sheight;
new_width = (int) ((double) (bwidth/100)*(sheight/((double) (bheight)/100)));
} else if(bwidth >= swidth && bheight >= sheight) {
new_width = swidth;
new_height = (int) ((double) (bheight/100)*(swidth/((double) (bwidth)/100)));
}
} else if(bwidth < bheight) {
if(bwidth > swidth && bheight > sheight) {
new_width = swidth;
new_height = (int) ((double) (bheight/100)*(swidth/((double) (bwidth)/100)));
} else if(bwidth < swidth && bheight > sheight) {
new_width = swidth;
new_height = (int) ((double) (bheight/100)*(swidth/((double) (bwidth)/100)));
} else if(bwidth < swidth && bheight < sheight) {
new_width = swidth;
new_height = (int) ((double) (bheight/100)*(swidth/((double) (bwidth)/100)));
} else if(bwidth < swidth && bheight < sheight) {
new_width = swidth;
new_height = (int) ((double) (bheight/100)*(swidth/((double) (bwidth)/100)));
} else if(bwidth >= swidth && bheight >= sheight) {
new_width = swidth;
new_height = (int) ((double) (bheight/100)*(swidth/((double) (bwidth)/100)));
}
}
答案 0 :(得分:9)
比较比率。
如果图像的宽高比大于屏幕的宽高比,那么您就知道您将使用屏幕宽度并计算高度。否则,您将使用屏幕高度并计算宽度。只要确保没有任何高度为零!
请注意,此处的代码会调整图像大小,使其始终显示在屏幕上。这有效地消除了图像的任何其他部分。要在完全可见的情况下使图像尽可能大,请将第一行中的<
更改为>
。
if (bwidth / bheight < swidth / sheight) {
new_width = swidth;
new_height = (int) Math.floor((double) bheight
* (double) swidth / (double) bwidth);
} else {
new_height = sheight;
new_width = (int) Math.floor((double) bwidth
* (double) sheight / (double) bheight);
}
我还做了一些改进:
Math.floor
代替int
的类型转换,以确保它不会向上舍入。答案 1 :(得分:-2)
非常感谢@Erick Robinson 改变了一点,但现在它有效!
以下是更改后的代码:
if (bwidth / swidth < bheight / sheight) {
new_width = swidth;
new_height = (int) Math.floor((double) bheight
* (double) swidth / (double) bwidth);
} else {
new_height = sheight;
new_width = (int) Math.floor((double) bwidth
* (double) sheight / (double) bheight);
}