在尝试从URL加载图像时,图像尺寸不一致,这是一些奇怪的行为,只有在后台加载图像然后等待进度时,图像才具有完整尺寸。为了分析这种情况,我在下面创建了JUnit测试。后台模式下的预期大小与加载的图像大小不一致。
为什么图像大小取决于图像是否在后台加载?
@Test
public void testImage() throws InterruptedException {
// do not exit on close of last window
// https://stackoverflow.com/a/10217157/1497139
Platform.setImplicitExit(false);
/// https://stackoverflow.com/a/38883432/1497139
// http://www.programcreek.com/java-api-examples/index.php?api=com.sun.javafx.application.PlatformImpl
com.sun.javafx.application.PlatformImpl.startup(() -> {
});
String urls[] = {
"https://upload.wikimedia.org/wikipedia/commons/thumb/b/ba/Flag_of_Germany.svg/320px-Flag_of_Germany.svg.png",
"https://via.placeholder.com/50x50" };
int expectedWidth[][] = { { 160, 25 }, { 320, 50 } };
int expectedHeight[][] = { { 96, 251 }, { 192, 50 } };
boolean backgrounds[] = { false, true };
int i = 0;
for (boolean background : backgrounds) {
int j=0;
for (String url : urls) {
Image image = new Image(url, background);
assertNotNull(image);
if (background)
while (image.getProgress() < 1)
Thread.sleep(40);
assertEquals("w " + i+ ","+j, expectedWidth[i][j], image.getWidth(), 0.1);
assertEquals("h " + i+ ","+j, expectedHeight[i][j], image.getHeight(), 0.1);
j++;
}
i++;
}
}