我做了一个java Paint应用程序,我做了一个彩虹画笔功能;但是,我想让随机颜色变成平滑的渐变。目前它只打印不同颜色的椭圆形,您可以注意到每个不同的椭圆形。有没有办法让它变成渐变?
Paint Project - CLICK HERE TO SEE PROGRAM
我的彩虹功能:
public void rainbow() {
Random generator = new Random();
int r = generator.nextInt(256);
int g = generator.nextInt(256);
int b = generator.nextInt(256);
Color color = new Color(r, g, b);
g2.setPaint(color);
}
我的鼠标监听器:
public DrawArea() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
// save coord x,y when mouse is pressed
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
// coord x,y when drag mouse
currentX = e.getX();
currentY = e.getY();
if (g2 != null) {
// draw oval if g2 context not null
g2.drawOval(oldX, oldY, 40, 40);
g2.fillOval(oldX, oldY, 40, 40);
// refresh draw area to repaint
repaint();
// store current coords x,y as olds x,y
oldX = currentX;
oldY = currentY;
}
}
});
}
绘制组件:
public void paintComponent(Graphics g) {
if (image == null) {
image = createImage(getSize().width, getSize().height);
g2 = (Graphics2D) image.getGraphics();
clear();
}
// enable antialiasing
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(image, 0, 0, null);
}
最佳答案
我认为你每次都会调用你的彩虹函数,这就是为什么你会得到这样的效果。
为了产生渐变的错觉,r、g、b 值的变化必须足够慢才能达到所需的效果。
实现此目的的一种方法是存储您想要 LERP 的值(请参阅: https://en.wikipedia.org/wiki/Linear_interpolation )。
//declare a variable to store the destinated Color;
public Color colorToBeLerped = null;
public Color currentColor = null;
public Color originalColor = null;
public final float deltaFactor = 0.2;
public void rainbow() {
if(currentColor==null||currentColor.equals(colorToBeLerped)){
Random generator = new Random();
int r = generator.nextInt(256);
int g = generator.nextInt(256);
int b = generator.nextInt(256);
colorToBeLerped = new Color(r, g, b);
originalColor = colorToBeLerped;
}
if(currentColor==null){
currentColor=colorToBeLerped;
}else{
//using the Color constructor that accepts float arguments, divide 255
currentColor= new Color((colorToBeLerped.getRed()-originalColor.getRed()*deltaFactor)/255,
(colorToBeLerped.getGreen()-originalColor.getGreen()*deltaFactor)/255,
(colorToBeLerped.getBlue()-originalColor.getBlue()*deltaFactor)/255);
}
g2.setPaint(currentColor);
}
说明:
1.跟踪您想要调整的颜色、您当前所处的颜色以及调用随机函数时的原始颜色。
2.当我们第一次调用彩虹函数时,当前颜色将被设置为随机颜色。
3.对于每个刻度,如果当前颜色不是目标颜色,我们将增加原始颜色和目标颜色之间差异的 1/5。
4.恒定的增量因子 0.2 意味着我们需要 5 个刻度才能从一种颜色变为另一种颜色,该变量越小,从原始颜色到目标颜色的时间越长。
5.如果我们已经达到了该颜色,我们将选择另一个新的目标颜色。
*未经测试,但我认为你可以弄清楚其余的
关于Java-制作渐变画笔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33539732/