Jam*_*s_D 5

您可能不需要使用您描述的策略。您在 340x512 大小的单元格中显示图像,即 174,080 像素。图像存储是每像素 4 字节,所以这是每张图像 696,320 字节;其中 1500 个将消耗大约 1GB。您只需要确保以您正在显示的大小(而不是其原始大小)加载图像:

// imageViewList.add(new Image(url));
imageViewList.add(new Image(url, 340, 512, true, true, true));

如果您稍后需要全尺寸的图像(例如,如果您希望用户从网格视图中选择图像并将其显示在更大的窗格中),您只需要从 url 重新加载它。

如果您确实需要实施您描述的策略,请GridView开箱即用地支持该策略。只需保留 URL 列表,而不是Images,并GridCell根据需要使用自定义加载图像。这将消耗更少的内存,但代价是更多的 I/O(加载图像)和 CPU(解析图像格式)。

为图像 url 制作项目GridView,存储为字符串。

然后您可以执行以下操作:

GridView<String> gridView = new GridView<>();
gridView.getItems().addAll(getAllImageURLs());

gridView.setCellFactory(gv -> new GridCell<>() {
    private final ImageView imageView = new ImageView();

    {
        imageView.fitWidthProperty().bind(widthProperty());
        imageView.fitHeightProperty().bind(heightProperty());
        imageView.setPreserveRatio(true);
    }

    @Override
    protected void updateItem(String url, boolean empty) {
        super.updateItem(url, empty);
        if (empty || url == null) {
            setGraphic(null);
        } else {
            double w = getGridView().getCellWidth();
            double h = getGridView().getCellHeight();
            imageView.setImage(new Image(url, w, h, true, true, true));
            setGraphic(imageView);
        }
    }
});


protected List<String> getAllImageURLs(){

    return App.getCardService().getCardArray().stream()
            // isn't the first sort redundant here?
            .sorted(Comparator.paringInt(Card::getCost))
            .sorted(Comparator.paring(Card::isChampion).reversed())
            .map(card -> String.format(App.pictureFolderPath +"%s.png", card.getCardCode()))
            .collect(Collectors.toList());
}

更多推荐

create,GridView,visible,Images