How to fill a JavaFX Sphere with two Colors

后端 未结 2 1888
礼貌的吻别
礼貌的吻别 2021-01-23 05:46

How can I fill in JavaFX a 3D Sphere with a linear gradient like a 2d Circle? I work with the JavaFX Scene Builder.

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-23 06:13

    As @mohsenmadi has pointed out, the diffuse color doesn't allow you using other than one single color.

    But you can have different colors on the sphere by using an image as a diffuse map.

    Based on your first image, I've created this texture image (called diffuse.jpg, and placed under the same folder as the JavaFX class):

    diffuse image

    You can create now your bicolored sphere:

    @Override
    public void start(Stage primaryStage) throws Exception {
    
        // 3D
        Sphere sphere = new Sphere(5);
        PhongMaterial phongMaterial = new PhongMaterial();
        phongMaterial.setDiffuseMap(new Image(getClass().getResource("diffuse.jpg").toExternalForm()));
        sphere.setMaterial(phongMaterial);
        ...
    }
    

    So you will see this:

    sphere

    Note that you may have some side effects on the poles.

    You can also have a look at the FXyz project, a library with aditional JavaFX 3D complex shapes, and also complex texture options.

    For instance, you can use a density map to create the same effect you want, but without providing the texture image.

    Under org/fxyz/shapes/primitives you can find several primitives like SegmentedSphereMesh.

    Like an sphere you can create one giving the number of divisions, the crop divisions (0 in this case for x and y), the radiuos, and the center:

    SegmentedSphereMesh sphere = new SegmentedSphereMesh(200,0,0,100,new Point3D(0f,0f,0f));
    

    Now you can define the function:

    Function dens = p->p.y>0?1:0;
    

    and apply it, with the number of colors (2 in this case):

    sphere.setTextureModeVertices3D(2,dens);
    

    Now you will have this:

    Sphere FXyz

    Now you won't have side effects on the poles, and you could modify this function easily to other cases.

    Note that you can add create your own palette of colors or play with the HSB function under org/fxyz/utils/Palette.

提交回复
热议问题