首页 > 解决方案 > 将 JavaFX 图像裁剪为正方形或圆形

问题描述

我需要一个函数。

import javafx.scene.image.Image;

private Image cropImage(Image image) {
    // Cut Image to max Circle or square
    return Image;
}

重要的是我不想改变图像的比例,而是在图像中间切掉最大的圆形或正方形。我已经尝试了两天了。你能帮我解决这个问题吗?

非常感谢你。雷内

标签: javajavafx

解决方案


像这样的东西:

public class Main extends Application {

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

    @Override
    public void start(Stage stage) {
        Image img = new Image("https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Osias_Beert_the_Elder_-_Dishes_with_Oysters%2C_Fruit%2C_and_Wine_-_Google_Art_Project.jpg/350px-Osias_Beert_the_Elder_-_Dishes_with_Oysters%2C_Fruit%2C_and_Wine_-_Google_Art_Project.jpg");
        Image img2 = crop(img, false);
        Image img3 = crop(img, true);
        HBox box = new HBox(8, new ImageView(img),new ImageView(img2),new ImageView(img3));
        Scene scene = new Scene(box);
        stage.setScene(scene);
        stage.show();
    }

    private Image crop(Image img, boolean toCircle) {
        double d = Math.min(img.getWidth(),img.getHeight());
        double x = (d-img.getWidth())/2;
        double y = (d-img.getHeight())/2;
        Canvas canvas = new Canvas(d, d);
        GraphicsContext g = canvas.getGraphicsContext2D();
        if (toCircle) {
            g.fillOval(0, 0, d, d);
            g.setGlobalBlendMode(BlendMode.SRC_ATOP);
        }
        g.drawImage(img, x, y);
        return canvas.snapshot(null, null);
    }
}

推荐阅读