Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I linearly scale my pixel coloring?

Tags:

java

colors

So I have a project for class I am working on in which you have to create a GUI box filled with circles, except the middle 50% of the screen cannot be filled with circles. Also, the red color value of each circle scales linearly from top to bottom of the screen, 0 at the top, 255 at the bottom. Here is what it should look like:

Here's what I have. I tried doing 255/500 (500 is the height) in order to get a scaling factor which I would then use to multiply all my y coordinates by in order to get the specified red value and it worked. The answer to 255 / 500 is 0.51 and when I used 0.51 instead of y * (255 / getHeight()); it worked. I need it to work with any dimensions of the frame, however, so the 0.51 doesn't work. For some reason the y * (255 / getHeight()) does not work, it appears to be returning 0 as the circles are various shades of blue and green. What can i do to fix this?

The code I have:

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());
    }
}

I tried various iterations of the redValue code, swapping order, making a double and typecasting to int, and various other things but I couldn't get it to work. I'm sure its a small mistake that is messing everything up, but anyways thank you for the help regardless. I am using Android Studio, not sure if that really would impact anything.

like image 966
Biggytiny Avatar asked Nov 20 '25 00:11

Biggytiny


1 Answers

Replace this line

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

with

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

Just changing redValue to an double wouldn't change the fact that 255/getHeight() is integer division.

like image 149
k_g Avatar answered Nov 22 '25 16:11

k_g