Appletなどで色を指定するには Color クラスを使います。
Color.black などの色名や RGB 値や HSB 値で色が指定できます。
HSB というのは耳慣れないかもしれないので,やや詳しく説明しておきます。
H は hue(色相)です。0→1と増やしていくと赤→緑→青→赤と変化します。周期関数ですので1→2でも同じです。
S は saturation(彩度)です。0→1と増やしていくと無彩色(白・灰色・黒)から有彩色に鮮やかさが増します。
B は brightness(明度)です。0→1と増やしていくと黒から明るい色へと変化します。
次の簡単なアプレットは,上の円が B = 1 での極座標 (S, 2πH) に相当する色を描きます。 下の長方形は S = 1 での横軸 H,縦軸 B に相当する色です。
import java.awt.*;
import javax.swing.*;
public class Colors extends JApplet {
Image img;
public void init() {
int width = getWidth();
int height = getHeight();
int r = (int)(width / (2 * Math.PI));
setContentPane(new MyPanel());
img = createImage(width, height);
Graphics g = img.getGraphics();
for (int i = 0; i < width; i++) {
double x = (double) i / r - 1.5 * Math.PI;
for (int j = 0; j < 2 * r; j++) {
double y = (j - r + 0.5) / r;
double d = Math.sqrt(x * x + y * y);
if (d <= 1.0) {
float h = (float)(Math.atan2(y, x) / (2 * Math.PI));
float s = (float) d;
g.setColor(Color.getHSBColor(h, s, 1f));
g.fillRect(i, 2 * r - 1 - j, 1, 1);
}
}
for (int j = 2 * r; j < height; j++) {
float h = (float) i / width;
float b = (float) (height - 1 - j) / (height - 1 - 2 * r);
g.setColor(Color.getHSBColor(h, 1f, b));
g.fillRect(i, j, 1, 1);
}
}
}
class MyPanel extends JPanel {
protected void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, this);
}
}
}
<applet code="Colors.class" width="500" height="300"> </applet>
Last modified: 2006-01-03 13:53:41