Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Revision as of 09:09, 8 June 2009 by tanjaluodes (Talk | contribs)

Draw Gradient in Java ME

From Wiki
Jump to: navigation, search


Here is a J2ME class for gradients drawing, supporting both horizontal and vertical gradients.

J2me gradients.jpg

This could be useful to substitute background gradient images with graphics drawn by code.

package com.jappit.wiki.gradientrect.graphics;
 
import javax.microedition.lcdui.Graphics;
 
public class Gradient
{
public static final int VERTICAL = 0;
public static final int HORIZONTAL = 1;
 
public static void gradientBox(Graphics g, int color1, int color2, int left, int top, int width, int height, int orientation)
{
int max = orientation == VERTICAL ? height : width;
 
for(int i = 0; i < max; i++)
{
int color = midColor(color1, color2, max * (max - 1 - i) / (max - 1), max);
 
g.setColor(color);
 
if(orientation == VERTICAL)
g.drawLine(left, top + i, left + width - 1, top + i);
else
g.drawLine(left + i, top, left + i, top + height - 1);
}
}
 
static int midColor(int color1, int color2, int prop, int max)
{
int red =
(((color1 >> 16) & 0xff) * prop +
((color2 >> 16) & 0xff) * (max - prop)) / max;
 
int green =
(((color1 >> 8) & 0xff) * prop +
((color2 >> 8) & 0xff) * (max - prop)) / max;
 
int blue =
(((color1 >> 0) & 0xff) * prop +
((color2 >> 0) & 0xff) * (max - prop)) / max;
 
int color = red << 16 | green << 8 | blue;
 
return color;
}
}

and here is a sample Canvas using the gradientBox method (the final effect is shown in the screenshot at beginning of this article):

package com.jappit.wiki.gradientrect.display;
 
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
 
import com.jappit.wiki.gradientrect.graphics.Gradient;
 
public class GradientRectCanvas extends Canvas {
 
protected void paint(Graphics g)
{
int halfWidth = getWidth() / 2;
int halfHeight = getHeight() / 2;
 
Gradient.gradientBox(g, 0xffffff, 0xff0000, 0, 0, halfWidth, halfHeight, Gradient.HORIZONTAL);
 
Gradient.gradientBox(g, 0xff0000, 0xffffff, halfWidth, 0, halfWidth, halfHeight, Gradient.VERTICAL);
 
Gradient.gradientBox(g, 0xffff00, 0x00ffff, 0, halfHeight, halfWidth, halfHeight, Gradient.VERTICAL);
 
Gradient.gradientBox(g, 0x00ff00, 0x0000ff, halfWidth, halfHeight, halfWidth, halfHeight, Gradient.VERTICAL);
}
 
}
118 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×