Swing 中的渐变颜色?

发布于 2025-01-11 21:30:20 字数 1577 浏览 4 评论 0原文

所以我添加了 8 个 TextFields 并想设置它们的背景颜色。我的想法是将第一个设置为红色 (255, 0, 0),最后一个设置为蓝色 (0, 0, 255),然后将 8 个(或实际上任何数字)设置为它们之间的其他渐变。我试图找出如何解决这个问题,“如果‘下一个’变量是 0,则增加该变量的数量与前一个变量的减少量相同”,

所以它在每次迭代中看起来可能是这样的:

setBackground(255, 0, 0);
setBackground(191, 63, 0);
setBackground(127, 127, 0);
...
setBackground(0, 0, 255); 

现在我想尝试将这种增加和减少的方式放入 for 循环中,该循环将迭代 n 次,其中 n 是文本字段的数量(为了简单起见,现在为 8)。有人知道是否有一个聪明的解决方案吗?

再次评论:

import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Apple{
    
    public Apple(int width, int height) {
        SwingUtilities.invokeLater(() -> initGUITest(width, height));
    }
    
    public void initGUITest(int width, int height) {
        JFrame frame = new JFrame();
        frame.setSize(width, height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
        
        JPanel panel = new JPanel();
        GridLayout gl = new GridLayout(10, 1);
        panel.setLayout(gl);
        
        frame.add(panel);
        
        for(int i = 0; i < 8; i++) {
            JTextField jtf = new JTextField("Track " + (i + 1));
            jtf.setBackground(new Color(255, 0, 0)); //Start color
            panel.add(jtf);
        }
        
    }
    
    public static void main(String args[]) {
        Apple a = new Apple(300, 300);
    }
}

So I add 8 TextFields and wanna set their background colors. My idea is to set the first one to red (255, 0, 0) the last one to blue (0, 0, 255) and the 8 (or any number actually) others gradient between these. I'm trying to figure out how to solve it in terms of "If the 'next' variable is 0 increase this variable with same amount as previous variable is decreasing with"

So it could look like in each iteration:

setBackground(255, 0, 0);
setBackground(191, 63, 0);
setBackground(127, 127, 0);
...
setBackground(0, 0, 255); 

Now I wanna try and fit this way of increase and decreasing into a for loop that will iterate n times where n is number of TextFields (now 8 for simplicity). Anyone know if there's a clever solution to this?

MRE:

import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Apple{
    
    public Apple(int width, int height) {
        SwingUtilities.invokeLater(() -> initGUITest(width, height));
    }
    
    public void initGUITest(int width, int height) {
        JFrame frame = new JFrame();
        frame.setSize(width, height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
        
        JPanel panel = new JPanel();
        GridLayout gl = new GridLayout(10, 1);
        panel.setLayout(gl);
        
        frame.add(panel);
        
        for(int i = 0; i < 8; i++) {
            JTextField jtf = new JTextField("Track " + (i + 1));
            jtf.setBackground(new Color(255, 0, 0)); //Start color
            panel.add(jtf);
        }
        
    }
    
    public static void main(String args[]) {
        Apple a = new Apple(300, 300);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡墨 2025-01-18 21:30:20

检查值是否为零并从那里递增或递减值的效率很低。

有两种方法可以实现此

线性

您计算一个混合值,即(i/stepSize),并使用它在开始值和结束值之间进行线性插值,如下

   intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
   intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
   intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);

转换混合到浮动对于插值在这里工作是必要的,这是逻辑

 private static void layout1(JFrame frame)
 {
  Color
  start=Color.RED,
  end=Color.BLUE;
  
  int[] intermediateColor=new int[3];
  
  int steps=8;
  float alpha;
  
  for(int i=0;i<=steps;i++)
  {
   JTextField field=new JTextField(10);
   
   alpha=((float)i/steps);
   
   intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
   intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
   intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);
  
   field.setBackground(new Color(intermediateColor[0],intermediateColor[1],intermediateColor[2]));
   
   frame.add(field);
  }
 }

输出:

在此处输入图像描述

关键帧

一个更复杂的示例涉及使用动态更改的关键帧基于您的 i 值的起点和终点

以下是关键帧,

 int[] checkPoints={0,2,4,6,8};
 Color[] colors={Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW,Color.MAGENTA};

这意味着对于

复选框 0->2 在 RED 和 RED 之间进行插值绿色

复选框 3->4 在绿色和绿色之间插入。蓝色

复选框 5->6 在蓝色和蓝色之间插入。黄色

复选框 7->8 在黄色和黄色之间插入。 MAGENTA

逻辑在于这段代码

 //loop through all checkpoints
  for(int j=0;j<checkPoints.length-1;j++)
   {
   //check if i lies in between these 2 checkpoints
    if(i>=checkPoints[j] && i<=checkPoints[j+1])
    {
      //interpolate between this & the next checkpoint
     checkPoint=j;
     start=colors[checkPoint];
     end=colors[checkPoint+1];
     //distance of i from start checkpoint/ total distance between checkpoints
     alpha=(float)(i-checkPoints[checkPoint])/(checkPoints[checkPoint+1]-checkPoints[checkPoint]);
    }
   } 

这是完整的代码

public class Test 
{
 public static void main(String[] args) 
 {
  JFrame frame=new JFrame("TEST");
  
  frame.setContentPane(new JPanel(new FlowLayout(FlowLayout.LEADING,10,0)));
  
  layout2(frame);
  
  frame.pack();
  
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  frame.setVisible(true);
 }
 
 private static void layout1(JFrame frame)
 {
  Color
  start=Color.RED,
  end=Color.BLUE;
  
  int[] intermediateColor=new int[3];
  
  int steps=8;
  float alpha;
  
  for(int i=0;i<=steps;i++)
  {
   JTextField field=new JTextField(10);
   
   alpha=((float)i/steps);
   
   intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
   intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
   intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);
  
   field.setBackground(new Color(intermediateColor[0],intermediateColor[1],intermediateColor[2]));
   
   frame.add(field);
  }
 }
 
 private static void layout2(JFrame frame)
 {
  int[] checkPoints={0,2,4,6,8};
  Color[] colors={Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW,Color.MAGENTA};
  
  int[] intermediateColor=new int[3];
  
  int steps=8;
  int checkPoint;
  float alpha=0;
  Color start=null,end=null;
  
  for(int i=0;i<=steps;i++)
  {
   JTextField field=new JTextField(10);
   
   for(int j=0;j<checkPoints.length-1;j++)
   {
    if(i>=checkPoints[j] && i<=checkPoints[j+1])
    {
     checkPoint=j;
     start=colors[checkPoint];
     end=colors[checkPoint+1];
     alpha=(float)(i-checkPoints[checkPoint])/(checkPoints[checkPoint+1]-checkPoints[checkPoint]);
    }
   } 
  
   
   intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
   intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
   intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);
  
   field.setBackground(new Color(intermediateColor[0],intermediateColor[1],intermediateColor[2]));
   
   frame.add(field);
  }
 }
}

输出:

在此处输入图像描述

Checking if an value is zero and incrementing or decrementing a value from there is inefficient.

There are 2 ways to go about this

Linear

you calculate an blend value which is (i/stepSize) and use that to linearly interpolate between the start and end value as follows

   intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
   intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
   intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);

conversion of blend to float is necessary for interpolation to work here is logic

 private static void layout1(JFrame frame)
 {
  Color
  start=Color.RED,
  end=Color.BLUE;
  
  int[] intermediateColor=new int[3];
  
  int steps=8;
  float alpha;
  
  for(int i=0;i<=steps;i++)
  {
   JTextField field=new JTextField(10);
   
   alpha=((float)i/steps);
   
   intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
   intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
   intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);
  
   field.setBackground(new Color(intermediateColor[0],intermediateColor[1],intermediateColor[2]));
   
   frame.add(field);
  }
 }

Output :

enter image description here

KeyFrames

An more complicated example involves using key frames where you dynamically change the start and end points based on your i value

Here are the keyframes

 int[] checkPoints={0,2,4,6,8};
 Color[] colors={Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW,Color.MAGENTA};

what this means is that for

checkboxes 0->2 interpolate between RED & GREEN

checkboxes 3->4 interpolate between GREEN & BLUE

checkboxes 5->6 interpolate between BLUE & YELLOW

checkboxes 7->8 interpolate between YELLOW & MAGENTA

The logic lies in this code

 //loop through all checkpoints
  for(int j=0;j<checkPoints.length-1;j++)
   {
   //check if i lies in between these 2 checkpoints
    if(i>=checkPoints[j] && i<=checkPoints[j+1])
    {
      //interpolate between this & the next checkpoint
     checkPoint=j;
     start=colors[checkPoint];
     end=colors[checkPoint+1];
     //distance of i from start checkpoint/ total distance between checkpoints
     alpha=(float)(i-checkPoints[checkPoint])/(checkPoints[checkPoint+1]-checkPoints[checkPoint]);
    }
   } 

Here is the full code

public class Test 
{
 public static void main(String[] args) 
 {
  JFrame frame=new JFrame("TEST");
  
  frame.setContentPane(new JPanel(new FlowLayout(FlowLayout.LEADING,10,0)));
  
  layout2(frame);
  
  frame.pack();
  
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  frame.setVisible(true);
 }
 
 private static void layout1(JFrame frame)
 {
  Color
  start=Color.RED,
  end=Color.BLUE;
  
  int[] intermediateColor=new int[3];
  
  int steps=8;
  float alpha;
  
  for(int i=0;i<=steps;i++)
  {
   JTextField field=new JTextField(10);
   
   alpha=((float)i/steps);
   
   intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
   intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
   intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);
  
   field.setBackground(new Color(intermediateColor[0],intermediateColor[1],intermediateColor[2]));
   
   frame.add(field);
  }
 }
 
 private static void layout2(JFrame frame)
 {
  int[] checkPoints={0,2,4,6,8};
  Color[] colors={Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW,Color.MAGENTA};
  
  int[] intermediateColor=new int[3];
  
  int steps=8;
  int checkPoint;
  float alpha=0;
  Color start=null,end=null;
  
  for(int i=0;i<=steps;i++)
  {
   JTextField field=new JTextField(10);
   
   for(int j=0;j<checkPoints.length-1;j++)
   {
    if(i>=checkPoints[j] && i<=checkPoints[j+1])
    {
     checkPoint=j;
     start=colors[checkPoint];
     end=colors[checkPoint+1];
     alpha=(float)(i-checkPoints[checkPoint])/(checkPoints[checkPoint+1]-checkPoints[checkPoint]);
    }
   } 
  
   
   intermediateColor[0]=(int)(start.getRed()+(end.getRed()-start.getRed())*alpha);
   intermediateColor[1]=(int)(start.getGreen()+(end.getGreen()-start.getGreen())*alpha);
   intermediateColor[2]=(int)(start.getBlue()+(end.getBlue()-start.getBlue())*alpha);
  
   field.setBackground(new Color(intermediateColor[0],intermediateColor[1],intermediateColor[2]));
   
   frame.add(field);
  }
 }
}

Output :

enter image description here

陪你到最终 2025-01-18 21:30:20

因此,您可以通过多种方式执行此操作,但对我个人而言,我希望使用某种“混合”算法,该算法允许您建立所需的颜色“范围”,然后基于某个值(即索引或百分比),生成这些颜色的混合颜色(在范围内)。

例如...

在此处输入图像描述

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            ColorBlender blender = new ColorBlender(new float[] {0, 1}, new Color[] {Color.RED, Color.BLUE});
            for (int index = 0; index < 8; index++) {
                Color color = blender.blendedColorAt(index / 7f);
                System.out.println(color);
                JTextField textField = new JTextField(10);
                textField.setBackground(color);
                add(textField, gbc);
            }
        }

    }

    public class ColorBlender {

        private float[] fractions;
        private Color[] colors;

        public ColorBlender(float[] fractions, Color[] colors) {
            this.fractions = fractions;
            this.colors = colors;
        }

        public Color blendedColorAt(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;
        }

        protected 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;
        }

        protected 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;
        }
    }
}

好的,但我想混合三种颜色

好的,这不是问题。只需添加另一个“停止”和该停止的颜色,例如...

ColorBlender blender = new ColorBlender(new float[] {0f, 0.5f, 1f}, new Color[] {Color.RED, Color.YELLOW, Color.BLUE});

将产生...

< img src="https://i.sstatic.net/rOckI.png" alt="在此处输入图像描述">

想要添加更多字段吗?不用担心,只需将 Color color = Blender.blishedColorAt(index / 7f); 更改为 7f 即可成为预期字段的数量 - 1(记住,我们正在开始索引位于0

So, any number of ways you might do this, but for me, personally, I'd look towards using some kind of "blending" algorithm which would allow you to establish the "range" of colors you want and then based on some value (ie a index or percentage), generate a color which is blend of those colors (within the range).

For example...

enter image description here

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            ColorBlender blender = new ColorBlender(new float[] {0, 1}, new Color[] {Color.RED, Color.BLUE});
            for (int index = 0; index < 8; index++) {
                Color color = blender.blendedColorAt(index / 7f);
                System.out.println(color);
                JTextField textField = new JTextField(10);
                textField.setBackground(color);
                add(textField, gbc);
            }
        }

    }

    public class ColorBlender {

        private float[] fractions;
        private Color[] colors;

        public ColorBlender(float[] fractions, Color[] colors) {
            this.fractions = fractions;
            this.colors = colors;
        }

        public Color blendedColorAt(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;
        }

        protected 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;
        }

        protected 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;
        }
    }
}

Okay, but I want to blend between three colors

Okay, not an issue. Simply add another "stop" and the color for that stop, for example...

ColorBlender blender = new ColorBlender(new float[] {0f, 0.5f, 1f}, new Color[] {Color.RED, Color.YELLOW, Color.BLUE});

will produce...

enter image description here

Want to add more fields? No worries, just change Color color = blender.blendedColorAt(index / 7f); to so that 7f becomes the number of expected fields - 1 (remember, we're starting the index at 0 ????)

春庭雪 2025-01-18 21:30:20

这是一个可以生成一系列颜色的类,这些颜色可以按照给定的步骤数从一种颜色过渡到另一种颜色。

简单的用法是:

ColorTransition ct = new ColorTransition(Color.RED, Color.BLUE, 8);

如果您需要多次转换,您可以这样做:

ColorTransition ct = new ColorTransition(Color.RED, Color.BLUE, 8);
ct.transitionTo(Color.GREEN, 4);

然后从蓝色转换为绿色。

生成所有过渡颜色后,您可以单独访问它们:

import java.awt.*;
import javax.swing.*;
import java.util.*;

public class ColorTransition
{
    private ArrayList<Color> colors;

    public ColorTransition(Color startColor, Color endColor, int steps)
    {
        colors = new ArrayList<>(steps);
        colors.add( startColor );

        transitionTo(endColor, steps);
    }

    public void transitionTo(Color endColor, int steps)
    {
        Color startColor = colors.get(colors.size() - 1);

        float rDelta = endColor.getRed() - startColor.getRed();
        float gDelta = endColor.getGreen() - startColor.getGreen();
        float bDelta = endColor.getBlue() - startColor.getBlue();

        for (int i = 1; i < steps; i++)
        {
            float stepIncrement = (float)i / (steps - 1);

            int rValue = (int)(startColor.getRed() + (rDelta * stepIncrement));
            int gValue = (int)(startColor.getGreen() + (gDelta * stepIncrement));
            int bValue = (int)(startColor.getBlue() + (bDelta * stepIncrement));

            Color color = new Color(rValue, gValue, bValue);
            colors.add( color );
        }
    }

    public int size()
    {
        return colors.size();
    }

    public Color getColorAt(int index)
    {
        return colors.get( index );
    }

    private static void createAndShowGUI()
    {
        ColorTransition ct = new ColorTransition(Color.RED, Color.BLUE, 8);
//      ct.transitionTo(Color.GREEN, 4);

        JPanel panel = new JPanel( new GridLayout(0, 1) );

        for (int i = 0; i < ct.size(); i++)
        {
            JTextField textField = new JTextField(25);
            textField.setBackground( ct.getColorAt(i) );
            panel.add( textField );
        }

        JFrame frame = new JFrame("Color Transition");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
    }
}

Here is a class that can generate a series of colors that can transition from one color to another for a given number of steps.

Simple usage would be:

ColorTransition ct = new ColorTransition(Color.RED, Color.BLUE, 8);

If you need multiple transitions you could do:

ColorTransition ct = new ColorTransition(Color.RED, Color.BLUE, 8);
ct.transitionTo(Color.GREEN, 4);

which would then transition from BLUE to GREEN.

Once all the transition colors are generated you can access them separately:

import java.awt.*;
import javax.swing.*;
import java.util.*;

public class ColorTransition
{
    private ArrayList<Color> colors;

    public ColorTransition(Color startColor, Color endColor, int steps)
    {
        colors = new ArrayList<>(steps);
        colors.add( startColor );

        transitionTo(endColor, steps);
    }

    public void transitionTo(Color endColor, int steps)
    {
        Color startColor = colors.get(colors.size() - 1);

        float rDelta = endColor.getRed() - startColor.getRed();
        float gDelta = endColor.getGreen() - startColor.getGreen();
        float bDelta = endColor.getBlue() - startColor.getBlue();

        for (int i = 1; i < steps; i++)
        {
            float stepIncrement = (float)i / (steps - 1);

            int rValue = (int)(startColor.getRed() + (rDelta * stepIncrement));
            int gValue = (int)(startColor.getGreen() + (gDelta * stepIncrement));
            int bValue = (int)(startColor.getBlue() + (bDelta * stepIncrement));

            Color color = new Color(rValue, gValue, bValue);
            colors.add( color );
        }
    }

    public int size()
    {
        return colors.size();
    }

    public Color getColorAt(int index)
    {
        return colors.get( index );
    }

    private static void createAndShowGUI()
    {
        ColorTransition ct = new ColorTransition(Color.RED, Color.BLUE, 8);
//      ct.transitionTo(Color.GREEN, 4);

        JPanel panel = new JPanel( new GridLayout(0, 1) );

        for (int i = 0; i < ct.size(); i++)
        {
            JTextField textField = new JTextField(25);
            textField.setBackground( ct.getColorAt(i) );
            panel.add( textField );
        }

        JFrame frame = new JFrame("Color Transition");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文