當你在索尼愛立信MIDP 2.0手機開發(fā)應用程序的時候,你可以使用一些系統(tǒng)字體的屬性來幫助你設置字體的外觀和布局。本文就是為大家介紹一下如何制作字體效果,包括漸變效果等。首先看看下圖展示的字體效果。
字體的外形是在創(chuàng)建Font類的時候指定的,請注意目前SonyEriCSSon的手機只實現了FACE_SYSTEM類型的字體,如果你創(chuàng)建的時候指定其他外觀也會自動使用FACE_SYSTEM。
Font font = Font.createFont(FONT.FACE_SYSTEM, FONT.SIZE_MEDIUM, FONT.STYLE_PLAIN);
可以在Canvas和CustomItem的界面中使用Font來裝飾界面,下面列舉幾個例子。
下面的代碼可以在Image上繪制文字,
Image fontImage = Image.createImage(width, height);
graphics = fontImage.getGraphics();
graphics.setFont(font);
graphics.setColor(0x00);
graphics.drawString("Hello World!", 0, 0, 0);
這樣在白色背景后面繪制了黑色的文字,如下:
當然,我們可以把圖片中白色的背景修改為透明的,這樣如果把Image畫到Canvas上的時候就不會顯得很突兀了(當Canvas的顏色和背景不一致的時候)。實現這個并不困難,你只需要修改Image的每個象素的Alpha值,修改為0即可。
int []data = new int[fontImage.getWidth() * fontImage.getHeight()];
fontImage.getRGB(data, 0, fontImage.getWidth(), 0, 0, fontImage.getWidth(), fontImage.getHeight());
for(int i=0; i<data.length; i++){
if(data[i]==backgroundColor){
data[i] = (data[i]&0x00FFFFFF);
}
}
同樣的道理,我們不只可以改變透明度,還可以改變圖片象素的顏色,這樣就可以實現字顏色的漸變了。下面的代碼可以實現顏色的改變,我們要做的就是循環(huán)改變圖片的像素值,請注意每一行使用一個顏色。
int []data = new int[fontImage.getWidth() * fontImage.getHeight()];
fontImage.getRGB(data, 0, fontImage.getWidth(), 0, 0, fontImage.getWidth(), fontImage.getHeight());
int newColor = fontColor;
int r = (fontColor & 0x00FF0000)>>16;
int g = (fontColor & 0x0000FF00)>>8;
int b = (fontColor & 0x000000FF);
int offsetR = r/fontImage.getHeight();
int offsetG = g/fontImage.getHeight();
int offsetB = b/fontImage.getHeight();
for(int i=0; i<data.length; i++){
if(data[i] != backgroundColor){
data[i] = newColor;
}
if(i%imageWidth == 0){ // suBTract each color on every row.
if(r>offsetR)
r -= offsetR;
if(g>offsetG)
g -= offsetG;
if(b>offsetB)
b -= offsetB;
newColor = 0xFF000000; // make the pixel opaque.
newColor += (r<<16);
newColor += (g<<8);
newColor += b;
}
}
如果想繪制等間距的文字,那么使用指定的寬度一個字符一個字符的畫,如下。
int charWidth = font.charWidth('W');
textWidth = charWidth * text.length();
fontImage = Image.createImage(width, weight);
graphics = fontImage.getGraphics();
graphics.setFont(font);
graphics.setColor(0x00);
for(int i=0; i<chars.length; i++){
graphics.drawChar(text.charAt(i),i*charWidth + charWidth/2, 0, Graphics.TOP Graphics.HCENTER);
}
原文地址 ,下載源碼
(出處:http://www.companysz.com)
新聞熱點
疑難解答