[英]How to fill an image in an imageView in javafx?
我在我的數據庫中保存了一個圖像,該圖像作為字節數組傳遞給圖像,然后加載到圖像視圖。 但是,我無法讓它填充 imageView。 我使用以下代碼:
package com.example.AppPrototipo.ui.tourist;
imports...
@Component
public class ExperienceController {
@FXML
Pane imagePane;
@FXML
ImageView imageViewPrincipal;
private final ExperienceRepository experienceRepository;
public ExperienceController(ExperienceRepository experienceRepository) {
this.experienceRepository = experienceRepository;
}
@FXML
private void initialize(){
Experience experience = experienceRepository.findById(1);
Image image = new Image(new ByteArrayInputStream(experience.getImages().get(0).getImageData()));
imageViewPrincipal.setImage(image);
imageViewPrincipal.fitWidthProperty().bind(imagePane.widthProperty());
imageViewPrincipal.fitHeightProperty().bind(imagePane.heightProperty());
}
}
所需的結果是圖像通過裁剪頂部和底部並保持居中來填充整個寬度(填充黑色側)。 有人可以幫助我嗎?
假設您將 ImageView 上的 preserveRatio 屬性設置為 true,並且正如matt所說的是他的評論,您只需要設置其中之一,比如 fitWidth,將使用圖像比例計算 fitHeight。
問題是圖像和窗格的比例不匹配,因此您需要使用setViewport進行一些裁剪,並且最好在窗格的高度或寬度發生變化時進行裁剪。
您需要做的是計算圖像的比例,並將其與窗格的比例進行比較,比較將讓您決定是否保留圖像的原始寬度或原始高度,您將計算另一個使用窗格的比率。
不確定這是否是最佳實踐,但這是我所描述的代碼
double oldImageWidth = image.getWidth(), oldImageHeight = image.getHeight(); //saving the original image size and ratio
double imageRatio = oldImageWidth / oldImageHeight;
imageViewPrincipal.setImage(image);
ChangeListener<Number> listener = (obs, ov, nv) -> {
double paneWidth = imagePane.getWidth();
double paneHeight = imagePane.getHeight();
double paneRatio = paneWidth / paneHeight; //calculating the new pane's ratio
//after width or height changed
double newImageWidth = oldImageWidth, newImageHeight = oldImageHeight;
if (paneRatio > imageRatio) {
newImageHeight = oldImageWidth / paneRatio;
} else if (paneRatio < imageRatio) {
newImageWidth = oldImageHeight * paneRatio;
}
imageViewPrincipal.setViewport(new Rectangle2D( // The rectangle used to crop
(oldImageWidth - newImageWidth) / 2, (oldImageHeight - newImageHeight) / 2, //MinX and MinY to crop from the center
newImageWidth, newImageHeight) // new width and height
);
imageViewPrincipal.setFitWidth(paneWidth);
};
imagePane.widthProperty().addListener(listener);
imagePane.heightProperty().addListener(listener);
這是它的外觀
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.