January 12, 2008
The Graphics.drawString() method in MIDP is pretty limited. You can specify a position, anchor point, and with the help of Graphics.setColor() and Graphics.setFont(), a color and a font, but that’s about it. However, its possible to do some simple text effects that are a bit more interesting by combining multiple calls to drawString().
First, lets take a quick look at the APIs involved. The drawString() method is pretty straightforward:
public void drawString(String str, int x, int y, int anchor);
The purposes of the str, x, and y parameters should be obvious. The anchor parameter defines how the text should be positioned in relation to the specified x and y coordinates. The accepted values are LEFT, HCENTER, RIGHT for the horizontal positioning, and TOP, BASELINE, and BOTTOM for the vertical positioning. These constants can be combined using the logical OR operator, e.g.:
g.drawString("Hello World", 100, 100,
Graphics.TOP | Graphics.HCENTER);
For our first effect, we will draw a string in a specified color with a black outline with the method below.
public void drawStringThick(
Graphics g, String str, int x, int y,
int anchor, int fillColor
) {
g.setColor(0x000000);
g.drawString(str, x + 1, y + 1, anchor);
g.drawString(str, x + 1, y - 1, anchor);
g.drawString(str, x - 1, y + 1, anchor);
g.drawString(str, x - 1, y - 1, anchor);
g.drawString(str, x + 2, y + 2, anchor);
g.drawString(str, x + 2, y - 2, anchor);
g.drawString(str, x - 2, y + 2, anchor);
g.drawString(str, x - 2, y - 2, anchor);
g.setColor(fillColor);
g.drawString(str, x, y, anchor);
}
The next method will draw a string with a pseudo-3D rainbow effect.
public void drawCrazyString(
int x, int y, Graphics g,
String msg, int anchor
) {
Font font = Font.getFont(
Font.FACE_PROPORTIONAL,
Font.STYLE_BOLD,
Font.SIZE_LARGE
);
g.setFont(font);
g.setColor(0x0000FF);
g.drawString(msg, x + 10, y + 10, anchor);
g.setColor(0x00FF00);
g.drawString(msg, x + 8, y + 8, anchor);
g.setColor(0xFFFF00);
g.drawString(msg, x + 6, y + 6, anchor);
g.setColor(0xFF7700);
g.drawString(msg, x + 4, y + 4, anchor);
g.setColor(0xFF0000);
g.drawString(msg, x + 2, y + 2, anchor);
g.setColor(0xFFFFFF);
g.drawString(msg, x, y, anchor);
}
With some creativity, you should be able to come up with other combinations of these method calls that will produce some interesting results. Happy coding!
Filed under Java ME Development