带循环的灰度/渐变

时间:2017-10-04 18:16:08

标签: java

我不知道从哪里开始。

使用循环绘制灰度和彩色渐变条。 在循环中使用switch语句。 使用嵌套for循环。

将代码添加到paintComponent()方法,以便应用程序生成渐变条,如上面的屏幕截图所示。 您需要从左到右绘制256个填充矩形以创建渐变。 每个矩形的颜色需要在每个红色,绿色和蓝色分量中改变1,以获得256个灰色阴影。 确保将窗口调整为多种尺寸,以检查渐变是否仍然完全覆盖窗口。

由于每个矩形的宽度必须是整数,当窗口大小不能被GRADIENT_DIVISIONS的数量整除时,我们会丢失每个矩形的一些宽度。例如,宽度为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 个答案:

没有答案