Andy B
Andy B

Reputation: 328

LinearGradientPaint getColor by val

so got a question involving linear gradients in Java, using multiple colors. I am looking to get an RGB color at any point along agradient. Creating the gradient and painting it is easy, and i can get the fractions and colors for those colors i set.....

The issue i have is that i want to get an RGB color at any point along the gradient. to break it down, an example application would be the creation and display of a gradient in some JPanel with size of 255 (maxSize=255 (see below)). depending on the size of said JPanel (maxSize) the interpolation would be different (larger number in maxSize would result in more interpolated values). I would like to be able to grab the RGB value at any location along the gradient, you could almost equate it to being able to do the following...

grab the RGB value based on the location in the gradient

RGB_Values = p.getColorByGradientLocation(float locationInGradient);

or

grab the RGB value based off a specific value, somewhere between Point2D start and Point2D end

RGB_Values = p.getColorByValue(float value);

e.g setting gradient code

Point2D start = new Point2D.Float(0, 0);
Point2D end = new Point2D.Float(0, maxSize);
Color[] colors = {n number of colors};
dist[] = ((float) i / (float) colors.length); //equally distributes colors
p = new LinearGradientPaint(start, end, dist, colors, CycleMethod.NO_CYCLE);

Many Thanks

Upvotes: 1

Views: 1204

Answers (1)

Andy B
Andy B

Reputation: 328

thanks to Nolo for the suggestion that help me figure out a method to do this. This is still in progress and i may find a better way to do this, but for now this works....

so you need to paint the lineargradient to a panel then paint the panel to an image (without displaying it).

BufferedImage bi = new BufferedImage(xSize, ySize, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
panel.print(g);

you need to set both the image and the panel to a width of 1, then height to match the gradient end (do 1 width for speed).

to display the gradient you can then grab just 1 pixel off each row, then use the image.getRGB(x,y) to get the pixel values in conjunction with the bit settings e.g

int rgb = im.getRGB(0, i);
r = (rgb >> 16) & 0xFF;
g = (rgb >> 8) & 0xFF;
b = (rgb & 0xFF);
Color newC = new Color(r, g, b);

if you loop through the image height using the above, you can get all the color values for a gradient you create.

:-)

Upvotes: 3

Related Questions