如何使重叠的形状产生新的颜色?

时间:2016-09-01 22:02:52

标签: java colors java-2d

我制作的游戏中会有红色和蓝色Shapes在屏幕上移动。对于如何使任何重叠不同的颜色(紫色),我看起来高低不一。我只使用Java2D,据我所知,它不支持着色器。我查看将红色形状绘制为一个BufferedImage,将蓝色形状绘制为另一个,然后尝试使用AlphaComposite组合颜色并将其绘制到屏幕上,但它从未产生正确的结果。我使用127,0,0和0,0,127代替红色和蓝色而不是255代,因为在我看来,255,0,255看起来对紫色很可怕。我实际上会喜欢this

1 个答案:

答案 0 :(得分:0)

感谢copeg的建议,我能够弄清楚。这是代码段(上下文:我正在绘制的形状是攻击):

    //Attacks
    BufferedImage attackImg = new BufferedImage(S_WIDTH, S_HEIGHT, BufferedImage.TYPE_INT_ARGB);
    Graphics2D ag = (Graphics2D) attackImg.getGraphics();
    //Make all of attackImg a transparent image
    ag.setComposite(AlphaComposite.Clear);
    ag.fillRect(0, 0, S_WIDTH, S_HEIGHT);
    ag.setComposite(AlphaComposite.SrcOver);

    //Render red attacks to attackImg
    ag.setColor(new Color(127, 0, 0, 255));
    for(Shape s : redAttacks)
        ag.fill(s);

    //Render overlap areas using composites to attackImg
    ag.setColor(new Color(127, 0, 127, 255));
    ag.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN));
    g.setColor(new Color(0, 0, 127, 255));
    for(Shape s : blueAttacks)
    {
        ag.fill(s);
        g.fill(s); //Render blue attacks
    }
    //Render red and purple attacks
    g.drawImage(attackImg, 0, 0, null);