带循环的java灰度/渐变
我不知道从哪里开始
使用循环绘制灰度和彩色渐变条。 在循环中使用switch语句。 使用嵌套循环
向paintComponent()方法添加代码,以便应用程序生成渐变条,如上面的屏幕截图所示。 你需要从左到右绘制256个填充矩形来创建渐变。 每个矩形的颜色需要在每个红色、绿色和蓝色分量中改变1,以获得256个灰度。 确保将窗口调整为几个大小,以检查渐变是否仍然完全覆盖窗口
因为每个矩形的宽度必须是一个整数,所以当窗口大小不能被梯度分割数平均分割时,我们会损失每个矩形的一些宽度。例如,843像素/256个分区的宽度=3.488。当它被截断为整数时,每个矩形的宽度变为3。如果我们取每个矩形的剩余部分,.488,乘以矩形的总数,我们得到125个像素。这很重要,你会在屏幕右侧看到缺失的宽度。 要解决这个问题,需要使用浮点除法、四舍五入(提示:Math.ceil),然后将结果转换回整数。例如,我们希望有843个像素/256个分区=3.488。然后使用天花板四舍五入到4.0。最后,我们将在使用前将结果转换回整数
代码:
package lab07;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Draws gradients across the width of the panel
* @author
*/
@SuppressWarnings("serial")
public class GradientLooperGrayscale extends JPanel {
/* This method draws on the Graphics context.
* This is where your work will be.
*
* (non-Javadoc)
* @see java.awt.Container#paint(java.awt.Graphics)
*/
public void paintComponent(Graphics canvas)
{
//ready to paint
super.paintComponent(canvas);
//account for changes to window size
int width = getWidth(); // panel width
int height = getHeight(); // panel height
final int GRADIENT_DIVISIONS = 256;
final int NUM_GRADIENT_BARS = 1;
//TODO: Your code goes here
}
/**
* DO NOT MODIFY
* Constructor for the display panel initializes
* necessary variables. Only called once, when the
* program first begins.
*/
public GradientLooperGrayscale()
{
setBackground(Color.black);
int initWidth = 768;
int initHeight = 512;
setPreferredSize(new Dimension(initWidth, initHeight));
this.setDoubleBuffered(true);
}
/**
* DO NOT MODIFY
* Starting point for the program
* @param args unused
*/
public static void main (String[] args)
{
JFrame frame = new JFrame ("GradientLooperGrayscale");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GradientLooperGrayscale());
frame.pack();
frame.setVisible(true);
}
}
共 (0) 个答案