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.

Draw Gradient in Java ME

From Wiki
Jump to: navigation, search

Here is a Java ME 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.

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;
int color1RGB[] = new int[]{(color1>>16) & 0xff,(color1>>8) & 0xff,color1 & 0xff};
int color2RGB[] = new int[]{(color2>>16) & 0xff,(color2>>8) & 0xff,color2 & 0xff};
int colorCalc[] = new int[]{
(( color2RGB[0] - color1RGB[0] )<<16)/max,
(( color2RGB[1] - color1RGB[1] )<<16)/max,
(( color2RGB[2] - color1RGB[2] )<<16)/max
for(int i = max; i > -1; i--)
(color1RGB[0]+((i*colorCalc[0])>>16)) <<16 |
(color1RGB[1]+((i*colorCalc[1])>>16)) <<8 |
if(orientation == VERTICAL)
g.drawLine(left, top + i, left + width - 1, top + i);
g.drawLine(left + i, top, left + i, top + height - 1);

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

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
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);
Article Metadata
Code ExampleTested with
Devices(s): Nokia 7373, Nokia N82
Created: jappit (11 Apr 2008)
Updated: tiviinik (16 Jan 2012)
Last edited: hamishwillee (30 Jul 2013)
This page was last modified on 30 July 2013, at 07:47.
134 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.