簡體   English   中英

如何更改JavaFX中a.png圖像的顏色?

[英]How to change the color of a .png image in JavaFX?

我有一個這樣的PNG圖像:

在此處輸入圖像描述

如何在 JavaFX 中更改顏色?

您可以使用Lighting效果,這是一個示例:

Lighting lighting = new Lighting(new Light.Distant(45, 90, Color.RED));
ColorAdjust bright = new ColorAdjust(0, 1, 1, 1);
lighting.setContentInput(bright);
lighting.setSurfaceScale(0.0);

imageView.setEffect(lighting);

Output:

樣本輸出

我真的很喜歡 @MS 的解決方案,它使用了 Lighting。 但是,如果您想生成可重用的圖像來渲染多個 ImageView 節點,以下是一種可能的解決方案。

請注意,以下解決方案是通過保持透明像素來改變整個圖像的顏色。 可能如果您有白色背景圖像,您可以相應地調整代碼。

public static Image blendColor(final Image sourceImage, final Color blendColor) {
    final double r = blendColor.getRed();
    final double g = blendColor.getGreen();
    final double b = blendColor.getBlue();
    final int w = (int) sourceImage.getWidth();
    final int h = (int) sourceImage.getHeight();
    final WritableImage outputImage = new WritableImage(w, h);
    final PixelWriter writer = outputImage.getPixelWriter();
    final PixelReader reader = sourceImage.getPixelReader();
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            // Keeping the opacity of every pixel as it is.
            writer.setColor(x, y, new Color(r, g, b, reader.getColor(x, y).getOpacity()));
        }
    }
    return outputImage;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM