JavaFX 将图像裁剪成圆形

JavaFX Crop Image as a Circle

我想用透明背景圈出裁剪图像文件并重新保存。这是在 android 中工作的代码,但我是 JavaFX 的新手。这个代码从中心像一个圆圈一样裁剪图像。我想在 JavaFX 中执行此操作!

public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
    Bitmap finalBitmap;
    if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
        finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius, false);
    else
        finalBitmap = bitmap;
    Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(), finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, finalBitmap.getWidth(), finalBitmap.getHeight());

    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(Color.parseColor("#BAB399"));
    canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f, finalBitmap.getHeight() / 2 + 0.7f,
    finalBitmap.getWidth() / 2 + 0.1f, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(finalBitmap, rect, rect, paint);

    return output;
}

我自己找到解决办法放在这里

private Image getRoundImage(Image image, int radius) {
    int width = (int) image.getWidth();
    int height = (int) image.getHeight();

    WritableImage wImage = new WritableImage(radius * 2, radius * 2);
    PixelWriter pixelWriter = wImage.getPixelWriter();
    PixelReader pixelReader = image.getPixelReader();
    Color c1 = new Color(0, 0, 0, 0);

    int w = (width / 2);
    int h = (height / 2);
    int r = radius * radius;

    for (int i = (width / 2) - radius, k = 0; i < w + radius; i++, k++)
        for (int j = (height / 2) - radius, b = 0; j < h + radius; j++, b++) {
            if ((i - w) * (i - w) + (j - h) * (j - h) > r)
                pixelWriter.setColor(k, b, c1);
            else
                pixelWriter.setColor(k, b, pixelReader.getColor(i, j));
        }
    return wImage;
}

Node 的剪辑 属性:

Specifies a Node to use to define the clipping shape for this Node. This clipping Node is not a child of this Node in the scene graph sense. Rather, it is used to define the clip for this Node.

您可以通过以下方式使用它来实现您的目标:

private static Image getRoundedImage(Image image, double radius) {
    Circle clip = new Circle(image.getWidth() / 2, image.getHeight() / 2, radius);
    ImageView imageView = new ImageView(image);
    imageView.setClip(clip);
    SnapshotParameters parameters = new SnapshotParameters();
    parameters.setFill(Color.TRANSPARENT);
    return imageView.snapshot(parameters, null);
}