Draw Font Using Canvas Example
This example is used to draw the different types of font using Canvas class. The following line of code is used to show the different style, size and faces of font.
static final int[] styles = {Font.STYLE_PLAIN, Font.STYLE_BOLD, Font.STYLE_ITALIC}; static final int[] sizes = {Font.SIZE_SMALL, Font.SIZE_MEDIUM, Font.SIZE_LARGE}; static final int[] faces = {Font.FACE_SYSTEM, Font.FACE_MONOSPACE, Font.FACE_PROPORTIONAL};
Here we have set the different Faces for the text...
- FACE_MONOSPACE
- FACE_PROPORTIONAL
- FACE_SYSTEM
Now we are setting their size
- SIZE_LARGE
- SIZE_MEDIUM
- SIZE_SMALL
and the style of the text
- STYLE_BOLD
- STYLE_ITALIC
- STYLE_PLAIN
- STYLE_UNDERLINED
Following methods is used in this class are:
Methods | Variable Types |
charsWidth(char[] ch, int offset, int length) | int |
charWidth(char ch) | int |
getBaselinePosition() | int |
getDefaultFont() | int |
getFace() | int |
getFont(int face, int style, int size) | Font |
getHeight() | int |
getSize() | int |
getStyle() | int |
isBold() | boolean |
isItalic() | boolean |
isPlain() | boolean |
isUnderlined() | boolean |
stringWidth(String str) | int |
substringWidth(String str, int offset, int len) | int |
The Application is as follows:
Source Code of DrawFont.java
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class DrawFont extends MIDlet{ private Display display; public void startApp(){ display = Display.getDisplay(this); display.setCurrent(new FontCanvas()); } public void pauseApp(){} public void destroyApp(boolean unconditional){} public void commandAction(){} } class FontCanvas extends Canvas{ static final int[] styles = {Font.STYLE_PLAIN, Font.STYLE_BOLD, Font.STYLE_ITALIC}; static final int[] sizes = {Font.SIZE_SMALL, Font.SIZE_MEDIUM, Font.SIZE_LARGE}; static final int[] faces = {Font.FACE_SYSTEM, Font.FACE_MONOSPACE, Font.FACE_PROPORTIONAL}; public void paint(Graphics g){ Font font = null; int y = 0; g.setColor(202, 238, 255); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(255, 87, 6); for(int size = 0; size < sizes.length; size++){ for(int face = 0; face < faces.length; face++){ int x = 0; for(int style = 0; style < styles.length; style++){ font = Font.getFont(faces [face], styles [style], sizes [size]); g.setFont(font); g.drawString(" Font ", x+1, y+1, Graphics.TOP | Graphics.LEFT); g.drawRect(x, y, font.stringWidth(" Font ") + 1, font.getHeight() + 1); x += font.stringWidth (" Font ") + 1; } y += font.getHeight() + 1; } } } }