3

ある色から別の色にフェードさせたいカスタムSwingコンポーネントをいくつか作成しています。現時点では、RGBからHSBに変換してから、色相値をインクリメントし、ペイントする前にRGBに変換し直していますが、問題ありません。

ただし、これはすべての色を循環します(つまり、青から緑にフェードしようとすると、黄色、オレンジ、赤などが循環します)。ある色から別の色に直接フェードする適切なアルゴリズム/方法はありますか?

編集:私はすでにスイングタイマーを介してそれを更新していました(私は疫病のようなスレッドでコンポーネントに触れることを避けようとします)。私はあなたの提案で今夜行きます、ありがとうみんな!

4

5 に答える 5

5

このに基づいて、以下は段階的にからへ、そして再びへとQueue<Color>循環します。これは、HSBモデルよりも数値的に少ないことに注意してください。HSBを使用したこの関連する例も参照してください。Color.greenColor.blueColor.greenN = 32Color.greenColor.blue

ここに画像の説明を入力してください

public Flash(JComponent component) {
    this.component = component;
    float gHue = Color.RGBtoHSB(0, 1, 0, null)[0];
    float bHue = Color.RGBtoHSB(0, 0, 1, null)[0];
    for (int i = 0; i < N; i++) {
        clut.add(Color.getHSBColor(gHue + (i * (bHue - gHue) / N), 1, 1));
    }
    for (int i = 0; i < N; i++) {
        clut.add(Color.getHSBColor(bHue - (i * (bHue - gHue) / N), 1, 1));
    }
}
于 2012-11-05T00:40:52.047 に答える
3

同じ結果を達成するために、アプローチを組み合わせて使用​​します。

基本的に、私は類似のAPIインターフェイスをとして使用しますLinearGradientPaint。ここでは、分数の配列と色の配列を指定し、floatパーセンテージに基づいて、結果のブレンド色を計算します。

これにより、同じアルゴリズムで多くの効果的な結果を生成できます。

ここに画像の説明を入力してください

この例は、さまざまな色のブレンドを示すように設計されていますが、2つの色と2つの色の一部を指定するだけで済み{0f, 1f}ます。

これにより、カラーアニメーションも効果的に行うことができます。

public class ColorFade {

    public static void main(String[] args) {
        new ColorFade();
    }

    public ColorFade() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
//                frame.add(new FadePane());
                frame.add(new ColorFadePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class FadePane extends JPanel {

        private float[] fractions = new float[]{0f, 0.25f, 0.5f, 1f};
        private Color[] colors = new Color[]{Color.GREEN, Color.BLUE, Color.YELLOW, Color.RED};
        private float direction = 0.05f;
        private float progress = 0f;

        public FadePane() {
            Timer timer = new Timer(125, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (progress + direction > 1f) {
                        direction = -0.05f;
                    } else if (progress + direction < 0f) {
                        direction = 0.05f;
                    }
                    progress += direction;
                    repaint();
                }
            });
            timer.setCoalesce(true);
            timer.setRepeats(true);
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(100, 100);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int width = getWidth();
            int height = getHeight();
            Color startColor = blendColors(fractions, colors, progress);
            g2d.setColor(startColor);
            g2d.fillRect(0, 0, width, height);
            g2d.dispose();
        }
    }

    public class ColorFadePane extends JPanel {

        private float[] fractions = new float[]{0f, 0.25f, 0.5f, 1f};
        private Color[] colors = new Color[]{Color.GREEN, Color.BLUE, Color.YELLOW, Color.RED};

        public ColorFadePane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 100);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();
            int width = getWidth();
            int height = getHeight();
            int bandWidth = width / 100;
            for (int index = 0; index < 100; index++) {
                float progress = (float)index / (float)100;
                Color color = blendColors(fractions, colors, progress);

                int x = bandWidth * index;
                int y = 0;
                g2d.setColor(color);
                g2d.fillRect(x, y, bandWidth, height);
            }
            g2d.dispose();
        }
    }

    public static Color blendColors(float[] fractions, Color[] colors, float progress) {
        Color color = null;
        if (fractions != null) {
            if (colors != null) {
                if (fractions.length == colors.length) {
                    int[] indicies = getFractionIndicies(fractions, progress);

                    float[] range = new float[]{fractions[indicies[0]], fractions[indicies[1]]};
                    Color[] colorRange = new Color[]{colors[indicies[0]], colors[indicies[1]]};

                    float max = range[1] - range[0];
                    float value = progress - range[0];
                    float weight = value / max;

                    color = blend(colorRange[0], colorRange[1], 1f - weight);
                } else {
                    throw new IllegalArgumentException("Fractions and colours must have equal number of elements");
                }
            } else {
                throw new IllegalArgumentException("Colours can't be null");
            }
        } else {
            throw new IllegalArgumentException("Fractions can't be null");
        }
        return color;
    }

    public static int[] getFractionIndicies(float[] fractions, float progress) {
        int[] range = new int[2];

        int startPoint = 0;
        while (startPoint < fractions.length && fractions[startPoint] <= progress) {
            startPoint++;
        }

        if (startPoint >= fractions.length) {
            startPoint = fractions.length - 1;
        }

        range[0] = startPoint - 1;
        range[1] = startPoint;

        return range;
    }

    public static Color blend(Color color1, Color color2, double ratio) {
        float r = (float) ratio;
        float ir = (float) 1.0 - r;

        float rgb1[] = new float[3];
        float rgb2[] = new float[3];

        color1.getColorComponents(rgb1);
        color2.getColorComponents(rgb2);

        float red = rgb1[0] * r + rgb2[0] * ir;
        float green = rgb1[1] * r + rgb2[1] * ir;
        float blue = rgb1[2] * r + rgb2[2] * ir;

        if (red < 0) {
            red = 0;
        } else if (red > 255) {
            red = 255;
        }
        if (green < 0) {
            green = 0;
        } else if (green > 255) {
            green = 255;
        }
        if (blue < 0) {
            blue = 0;
        } else if (blue > 255) {
            blue = 255;
        }

        Color color = null;
        try {
            color = new Color(red, green, blue);
        } catch (IllegalArgumentException exp) {
            NumberFormat nf = NumberFormat.getNumberInstance();
            System.out.println(nf.format(red) + "; " + nf.format(green) + "; " + nf.format(blue));
            exp.printStackTrace();
        }
        return color;
    }
}
于 2012-11-04T22:53:28.710 に答える
1

ヒント

  1. スローモーション効果のためにスイングタイマーを使用する
  2. RGBの値を数値でデクリメントします。x

Tadaaaa .. :-)

更新:必要に応じて、の値を試してみることができますx

関数を使用して、実行中にMath.Random()疑似乱数値を生成しますx

HovercraftFullOfEels&mKorbel、ご入力ありがとうございます

于 2012-11-04T21:30:35.447 に答える
1

最も簡単な方法は、各RGB値の間を補間することです。これはすべての言語で同じです-Pythonコードは次のようになります:

steps = 10

rgb1 = [ 'AA', '08', 'C3' ]
rgb2 = [ '03', '88', '1C' ]

h1 = map( lambda s: int( '0x'+s, 0 ), rgb1 )
h2 = map( lambda s: int( '0x'+s, 0 ), rgb2 )

inc = [0, 0, 0]
for i in range(0,3):
    inc[i] = ( h2[i] - h1[i] ) / ( steps - 1 )

for i in range(0,steps-1):
    print '<span style="background: #%02x%02x%02x"> &nbsp; %i &nbsp; </span>' % ( 
            h1[0] + i * inc[0],
            h1[1] + i * inc[1],
            h1[2] + i * inc[2],
            i+1 )

print '<span style="background: #%02x%02x%02x"> &nbsp; %i &nbsp; </span>' % ( 
        h2[0], h2[1], h2[2], steps )
于 2012-11-04T22:03:19.490 に答える
0

開始RGBカラーから最終的に必要なカラーへの遷移を線形補間することができます。

これは、たとえばrgb(255,255,0)、開始色とrgb(50,50,50)目標があり、5つのステップで最終的な色に到達したい場合(-41 = (255-50)/5, -41, 10)、次の色につながるすべてのステップで適応することを意味します。

rgb(255,255,  0)
rgb(214,214, 10)
rgb(173,173, 20)
rgb(132,132, 30)
rgb( 91, 91, 40)
rgb( 50, 50, 50)

これは線形グラデーションと呼ばれ、実装は非常に簡単ですが、もちろん、色の間の適切な遷移を行うためのさまざまな他の手法があります。

于 2012-11-04T21:32:49.930 に答える