J2ME Draw Gradient

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

Image: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, 100 * (max - 1 - i) / (max - 1));

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 red =
(((color1 >> 16) & 0xff) * prop +
((color2 >> 16) & 0xff) * (100 - prop)) / 100;

int green =
(((color1 >> 8) & 0xff) * prop +
((color2 >> 8) & 0xff) * (100 - prop)) / 100;

int blue =
(((color1 >> 0) & 0xff) * prop +
((color2 >> 0) & 0xff) * (100 - prop)) / 100;

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);
}
 
}
  性能上不如,polish的DrawUtil
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值