【问题标题】:How to change the color of a .png image in JavaFX?如何在 JavaFX 中更改 .png 图像的颜色?
【发布时间】:2020-05-18 20:48:51
【问题描述】:

我有一个这样的 PNG 图片:

如何在 JavaFX 中更改颜色?

【问题讨论】:

    标签: java javafx colors


    【解决方案1】:

    您可以使用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);
    

    输出:

    【讨论】:

      【解决方案2】:

      我真的很喜欢 @M.S 的解决方案,它使用了 Lighting。但是,如果您想生成一个可重用的 Image 来渲染多个 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;
      }
      

      【讨论】:

      • 谢谢!想找解决办法很久了
      猜你喜欢
      • 1970-01-01
      • 2014-02-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2011-08-28
      • 2016-07-12
      相关资源
      最近更新 更多