java - 将 JavaFX 图像裁剪为正方形或圆形
问题描述
我需要一个函数。
import javafx.scene.image.Image;
private Image cropImage(Image image) {
// Cut Image to max Circle or square
return Image;
}
重要的是我不想改变图像的比例,而是在图像中间切掉最大的圆形或正方形。我已经尝试了两天了。你能帮我解决这个问题吗?
非常感谢你。雷内
解决方案
像这样的东西:
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);
}
}
推荐阅读
- c++ - 多定义boost序列化
- reactjs - 带有反应项目的 Json ejsonparse 消息必须是实际的 json 而不是 JavaScript
- apache-spark - 如何使用 Scala 在 Jupyter 笔记本内的 UDF 中使用广播
- azure - 为什么“Microsoft.Web/sites”的“FileSystemUsage”指标总是返回零?
- javascript - React Native API 数据获取并保存为全局数据
- java - Kafka连接音频文件
- moodle - 具有固定和预先指定数量的正确和错误答案的问题
- php - Laravel - 从产品表中获取结果,我将结果与属性表匹配
- xamarin - 更新 Nuget 包后缺少 Xamarin 代码
- c# - 程序集 '' 引用程序集 'microsoft.sqlserver.dtsruntimewrap, ',它在当前数据库中不存在