在 Java 中创建随机颜色? [英] Creating random colour in Java?
问题描述
我想在 Java 应用程序的 JPanel 上绘制随机彩色点.有没有什么方法可以创建随机颜色?
I want to draw random coloured points on a JPanel in a Java application. Is there any method to create random colours?
推荐答案
使用随机库:
import java.util.Random;
然后创建一个随机生成器:
Then create a random generator:
Random rand = new Random();
由于颜色分为红绿蓝,您可以通过创建随机原色来创建新的随机颜色:
As colours are separated into red green and blue, you can create a new random colour by creating random primary colours:
// Java 'Color' class takes 3 floats, from 0 to 1.
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
然后为了最终创建颜色,将原色传递给构造函数:
Then to finally create the colour, pass the primary colours into the constructor:
Color randomColor = new Color(r, g, b);
<小时>
您还可以使用此方法创建不同的随机效果,例如创建更强调某些颜色的随机颜色……传入较少的绿色和蓝色以产生粉红色"随机颜色.
You can also create different random effects using this method, such as creating random colours with more emphasis on certain colours ... pass in less green and blue to produce a "pinker" random colour.
// Will produce a random colour with more red in it (usually "pink-ish")
float r = rand.nextFloat();
float g = rand.nextFloat() / 2f;
float b = rand.nextFloat() / 2f;
或者为了确保只生成浅"色,您可以生成每个颜色元素总是 > 0.5 的颜色:
Or to ensure that only "light" colours are generated, you can generate colours that are always > 0.5 of each colour element:
// Will produce only bright / light colours:
float r = rand.nextFloat() / 2f + 0.5;
float g = rand.nextFloat() / 2f + 0.5;
float b = rand.nextFloat() / 2f + 0.5;
Color
类还可以使用其他各种颜色函数,例如使颜色更亮:
There are various other colour functions that can be used with the Color
class, such as making the colour brighter:
randomColor.brighter();
可以在此处阅读 Color
类的概述:http://download.oracle.com/javase/6/docs/api/java/awt/Color.html
An overview of the Color
class can be read here: http://download.oracle.com/javase/6/docs/api/java/awt/Color.html
这篇关于在 Java 中创建随机颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!