JavaFX图像库类似于Picasso或Glide

时间:2019-03-09 05:49:29

标签: java caching javafx picasso glade

我正在寻找一个库,该库允许我以与Picasso或Android / Java的Glide相同的方式加载图像,我在使用JavaFX 2的桌面应用程序中工作,并且图像加载阻塞了主线程。我曾考虑过从头开始创建自定义功能,但是我想它们是一套成熟的工具,可以避免额外的工作。我曾尝试将图像加载到其线程内,但无法正常工作。

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
    final String thumbnail = data.getSong().getThumbnail();

    Runnable runnable = () -> {
        Image image = new Image(thumbnail);
        imageView.setImage(image);
    };
    runnable.run();
}

1 个答案:

答案 0 :(得分:0)

对于重复图像图像加载,我建议使用javafx动画工具之一。 PauseTransition是一种选择:

import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class SlideShow extends Application{

    private static int counter =0;
    private ImageView iv;
    private Image[] images;
    private Button swapImage;

    private final String[] urls = {
            "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/160/lg/57/tropical-fish_1f420.png",
            "https://www.shareicon.net/data/128x128/2015/03/28/14104_animal_256x256.png",
            "https://cdn1.iconfinder.com/data/icons/DarkGlass_Reworked/128x128/apps/gnome-fish.png",
            "http://www.iconsalot.com/asset/icons/freepik/pet-shop-13/128/010-fish-2-icon.png"
    };

    @Override
    public void start(Stage primaryStage) throws Exception
    {
        images = new Image[urls.length];
        for(int i=0; i< urls.length; i++) {
            images[i] = new Image(urls[i], true);
        }

        iv = new ImageView(images[counter++]);
        swapImage = new Button("Start");
        swapImage.setOnAction(e->update());
        BorderPane root = new BorderPane(iv);
        root.setBottom(new StackPane(swapImage));
        Scene scene = new Scene(root,200,200);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void update() {

        swapImage.setDisable(true);
        PauseTransition pause = new PauseTransition(Duration.seconds(1));
        pause.setOnFinished(event ->{
            swapImage();
            pause.play();
        });
        pause.play();   
    }

    private void swapImage() {
        counter = counter % images.length;
        iv.setImage(images[counter++]);
    }

    public static void main(String[] args)  {
        Application.launch(args);
    }
}

或者,您可以通过修改update()来使用Timeline

private void update() {

    swapImage.setDisable(true);
    KeyFrame keyFrame = new KeyFrame(
            Duration.seconds(1),
            event -> swapImage()
    );

    Timeline timeline = new Timeline();
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.getKeyFrames().add(keyFrame);
    timeline.play();
}