JavaFX生成空白单色图像 [英] JavaFX generate blank single color Image

查看:132
本文介绍了JavaFX生成空白单色图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成仅带有一种颜色的图像,以用于为PhongMaterials创建地图.像

I would like to generate an image with just one color on it, to use for creating maps for PhongMaterials. Something like

Image generateImage(int width, int height, double red, double green, double blue, double opacity);

我需要做什么才能做到这一点?虽然我更愿意纯粹按程序进行此操作,但是如果有办法通过给它一个空白的白色图像(例如

What do I need to do to make this? While I'd prefer to make this purely procedurally, if there's a way to do this by giving it a blank white image like https://dummyimage.com/600x400/ffffff/fff.png and changing its color, I would be okay with that too. I thought about just generating a URL and getting the image directly from that website, but I can't be dependent on internet connection for this to work (and besides, that website doesn't handle transparent images).

推荐答案

要返回指定的图像,可以执行以下操作:

To return an image as you specify, you can do:

public Image generateImage(int width, int height, double red, double green, double blue, double opacity) {
    WritableImage img = new WritableImage(width, height);
    PixelWriter pw = img.getPixelWriter();

    // Should really verify 0.0 <= red, green, blue, opacity <= 1.0        
    int alpha = (int) (opacity * 255) ;
    int r = (int) (red * 255) ;
    int g = (int) (green * 255) ;
    int b = (int) (blue * 255) ;

    int pixel = (alpha << 24) | (r << 16) | (g << 8) | b ;
    int[] pixels = new int[width * height];
    Arrays.fill(pixels, pixel);

    pw.setPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);
    return img ;
}

在几乎所有用例(我能想到的)中,您都可以创建一个1像素乘1像素的图像,然后即时进行缩放.如果足够,您可以将其简化为

In pretty much any use case (that I can think of), you may as well create an image that is 1 pixel by 1 pixel, and then scale it up on the fly. If this suffices, you can simplify this to

public Image generateImage(double red, double green, double blue, double opacity) {
    WritableImage img = new WritableImage(1, 1);
    PixelWriter pw = img.getPixelWriter();

    Color color = Color.color(red, green, blue, opacity);
    pw.setColor(0, 0, color);
    return img ;
}

然后,例如您可以这样做:

Then, e.g. you can do:

Image marshallUniGreen = generateImage(0, 177.0 / 255, 65.0 / 255, 1) ; 
ImageView imageView = new ImageView(marshallUniGreen);
imageView.setFitWidth(300);
imageView.setFitHeight(200);
imageView.setPreserveRatio(false);

这篇关于JavaFX生成空白单色图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆