【问题标题】:How do I linearly scale my pixel coloring?如何线性缩放像素着色?
【发布时间】:2015-02-23 22:22:46
【问题描述】:

所以我有一个我正在处理的课程项目,你必须创建一个填充圆圈的 GUI 框,除了屏幕的中间 50% 不能填充圆圈。此外,每个圆圈的红色值从屏幕的顶部到底部线性缩放,顶部为 0,底部为 255。它应该是这样的:

这就是我所拥有的。我尝试做 255/500(500 是高度)以获得一个比例因子,然后我将使用它来乘以我所有的 y 坐标以获得指定的红色值并且它起作用了。 255 / 500 的答案是 0.51,当我使用 0.51 而不是 y * (255 / getHeight());有效。但是,我需要它与框架的任何尺寸一起使用,因此 0.51 不起作用。由于某种原因, y * (255 / getHeight()) 不起作用,它似乎返回 0,因为圆圈是各种深浅不一的蓝色和绿色。我该怎么做才能解决这个问题?

我的代码:

public class NewJComponent1 extends JComponent {
    public void paintComponent(Graphics g) {
        int count = 0;
        int diameter = 0;
        Random rand = new Random();

        while (count < 5000) {
            int x = rand.nextInt(getWidth() + 1);
            int y = rand.nextInt(getHeight() + 1);
            int greenValue = rand.nextInt(256);
            int blueValue = rand.nextInt(256);
            diameter = rand.nextInt(21) + 10;

            int redValue = y * (255 / getHeight());
            Color random = new Color (redValue, greenValue, blueValue);

            if ((x < (getWidth() / 4) && y <= (getHeight() - diameter))
                || ((x > (getWidth() * .75) && (x < getWidth() - diameter)) && y <= (getHeight() - diameter))
                || (x <= (getWidth() - diameter) && y < (getHeight() / 4))
                || (x <= (getWidth() - diameter) && ((y > (getHeight() * .75)) && (y <= getHeight() - diameter)))){

                g.setColor(random);
                g.fillOval(x, y, diameter, diameter);
                count++;
            }
        }
        System.out.println(getHeight());
        System.out.println(getWidth());
    }
}

我尝试了 redValue 代码的各种迭代、交换顺序、制作双精度和类型转换为 int 以及各种其他事情,但我无法让它工作。我敢肯定这是一个小错误,把一切都搞砸了,但无论如何,谢谢你的帮助。我正在使用 Android Studio,不确定这是否真的会影响任何事情。

【问题讨论】:

  • int redValue = (int)( y * ( 255.0 / getHeight() ) ); 关键是除法的操作数之一必须是浮点类型,所以即使double redValue = 255 / getHeight(); 也会给你一个redValue 0.0
  • 在另一个方面,请注意您的屏幕可以划分为 4x4 矩形,并且您不能只绘制其中的 4 个。你可以建立一个例程,其中中心部分永远不会考虑被吸引到。 (一个小得多的优化是您可以先测试中心,然后才能选择颜色。)

标签: java colors


【解决方案1】:

替换这一行

int redValue = y * (255 / getHeight());

int redValue = (int) Math.round(y * (255.0 / (double) getHeight()));

只是将redValue 更改为double 不会改变255/getHeight() 是整数除法这一事实。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2013-11-19
    • 1970-01-01
    相关资源
    最近更新 更多