将 JavaFX 图像裁剪为正方形或圆形
Crop JavaFX Image to square or Circle
我需要一个功能。
import javafx.scene.image.Image;
private Image cropImage(Image image) {
// Cut Image to max Circle or square
return Image;
}
重要的是我不想改变图像的比例而是在图像中间切割最大的圆或正方形。
这两天我一直在尝试这样做。
你能帮我解决这个问题吗?
非常感谢。雷内
您可以通过 ImageView
的 setClip
方法来做到这一点。
像这样:
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);
}
}
我需要一个功能。
import javafx.scene.image.Image;
private Image cropImage(Image image) {
// Cut Image to max Circle or square
return Image;
}
重要的是我不想改变图像的比例而是在图像中间切割最大的圆或正方形。 这两天我一直在尝试这样做。 你能帮我解决这个问题吗?
非常感谢。雷内
您可以通过 ImageView
的 setClip
方法来做到这一点。
像这样:
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);
}
}