我做了一个简单的例子来向你展示一种可能的方法,它利用getRGBColorComponents()
了 Color 类的方法。
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test extends JFrame {
public Test(Color c1, Color c2) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 200);
setVisible(true);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel.add(new JLabel(createColorIcon(c1)));
panel.add(new JLabel(createColorIcon(c2)));
add(panel);
}
public ImageIcon createColorIcon(Color c) {
int w = 44, h = 20;
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
if (c != null) {
g.setColor(c);
g.fillRect(0, 0, w, h);
} else {
g.setColor(Color.GRAY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawLine(1, 1, w - 2, h - 2);
g.drawLine(1, h - 2, w - 2, 1);
}
g.setColor(Color.GRAY);
g.drawRect(0, 0, w - 1, h - 1);
g.dispose();
return new ImageIcon(bi);
}
public static void main(String[] args) {
Color c1 = Color.decode("0xFF0000");
float[] f = c1.getRGBColorComponents(null);
System.out.println(f.length);
for (int i = 0; i < f.length; i++) {
System.out.println(f[i]);
}
f[0] = f[0] * 0.8f;
Color c2 = new Color(f[0],f[1],f[2]);
new Test(c1,c2);
}
}
您只需调用该getRGBColorComponents()
方法,您就会得到一个数组,其中红色、绿色和蓝色的颜色值是 0.0 到 1.0 范围内的浮点值,其中 255(或 0xFF)的 int 值对应于 1.0 浮点值。正如我在示例末尾所做的那样,您只需将其与您选择的因子相乘即可。