Cocos2d-x android Games use your own Fonts

Source: Internet
Author: User
Tags android games

In the use of cocos2d-x to release Android platform games, the game may need to display Chinese fonts, or want to display beautiful custom fonts, what should I do?
The font label in the cocos2d-x provides the CCLabelAtlas, CCLabelBMFont CCLabelTTF

1. CCLabelAtlas is fast and supports a limited set of characters or numbers.

2. CCLabelBMFont
We can use CCLabelBMFont to load the. plist file generated by the font editor. However, this method is time-consuming and laborious when many texts are displayed.
For example, we want to show details about the game.

3. CCLabelTTF
You can select a font to display text, but only the default font in the system is supported.
CCLabelTTF * pLabel = CCLabelTTF: create ("Hello World", "Arial", 24 );

Question: What should we do if we want to display the game story in an Android game and use a specific font gril. ttf (non-system default font )?

In fact, cocos2d-x has provided help us achieve
Construct the name specified in CCLabelTTF and pass it to CCTexture2D.
Void CCLabelTTF: updateTexture ()
{
CCTexture2D * tex;
If (m_tDimensions.width = 0 | m_tDimensions.height = 0)
{
Tex = new CCTexture2D ();
Tex-> initWithString (m_string.c_str (), m_pFontName-> c_str (), m_fFontSize * CC_CONTENT_SCALE_FACTOR ());
}
Else
{
Tex = new CCTexture2D ();
Tex-> initWithString (m_string.c_str (),
CC_SIZE_POINTS_TO_PIXELS (m_tDimensions ),
M_hAlignment,
M_vAlignment,
M_pFontName-> c_str (),
M_fFontSize * CC_CONTENT_SCALE_FACTOR ());
}

.
}
CCTexture2D again passed the body name to CCImage
(PS: The CCImage class (./platform/android/CCImage. h) on the android platform is called)
Instead of the CCImage class (./platform/win32/CCImage. h) on the win32 platform ))

CCImage on android
Bool CCImage: initWithString (
Const char * pText,
Int nWidth/* = 0 */,
Int nHeight/* = 0 */,
ETextAlign eAlignMask/* = kAlignCenter */,
Const char * pFontName/* = nil */,
Int nSize/* = 0 */)
{
Bool bRet = false;

Do
{
CC_BREAK_IF (! PText );

BitmapDC & dc = sharedBitmapDC ();

CC_BREAK_IF (! Dc. getBitmapFromJava (pText, nWidth, nHeight, eAlignMask, pFontName, nSize ));

// Assign the dc. m_pData to m_pData in order to save time
M_pData = dc. m_pData;
CC_BREAK_IF (! M_pData );

M_nWidth = (short) dc. m_nWidth;
M_nHeight = (short) dc. m_nHeight;
M_bHasAlpha = true;
M_bPreMulti = true;
M_nBitsPerComponent = 8;

BRet = true;
} While (0 );

Return bRet;
}

Then, the BitmapDC of the android platform is called.
Bool getBitmapFromJava (const char * text, int nWidth, int nHeight, CCImage: ETextAlign eAlignMask, const char * pFontName, float fontSize)
{
JniMethodInfo methodInfo;
If (! JniHelper: getStaticMethodInfo (methodInfo, "org/cocos2dx/lib/Cocos2dxBitmap", "createTextBitmap ",
"(Ljava/lang/String; IIII) V "))
{
CCLOG ("% s % d: error to get methodInfo", _ FILE __, _ LINE __);
Return false;
}


}

The createTextBitmap function in the JAVA code Cocos2dxBitmap. java is called.

/*
* @ Width: the width to draw, it can be 0
* @ Height: the height to draw, it can be 0
*/
Public static void createTextBitmap (String content, String fontName,
Int fontSize, int alignment, int width, int height ){

Content = refactorString (content );
Paint paint = newPaint (fontName, fontSize, alignment );

TextProperty textProperty = computeTextProperty (content, paint, width, height );

Int bitmapTotalHeight = (height = 0? TextProperty. totalHeight: height );

// Draw text to bitmap
Bitmap bitmap = Bitmap. createBitmap (textProperty. maxWidth,
BitmapTotalHeight, Bitmap. Config. ARGB_8888 );
Canvas canvas = new Canvas (bitmap );

// Draw string
FontMetricsInt fm = paint. getFontMetricsInt ();
Int x = 0;
Int y = computeY (fm, height, textProperty. totalHeight, alignment );
String [] lines = textProperty. lines;
For (String line: lines ){
X = computeX (paint, line, textProperty. maxWidth, alignment );
Canvas. drawText (line, x, y, paint );
Y + = textProperty. heightPerLine;
}

InitNativeObject (bitmap );
}

The newPaint function calls the font loading function.
Private static Paint newPaint (String fontName, int fontSize, int alignment ){
Paint paint = new Paint ();
Paint. setColor (Color. WHITE );
Paint. setTextSize (fontSize );
Paint. setAntiAlias (true );

/*
* Set type face for paint, now it support. ttf file.
*/
If (fontName. endsWith (". ttf") {// The font needs to end with. ttf.
Try {
// Typeface typeFace = Typeface. createFromAsset (context. getAssets (), fontName );
Typeface typeFace = Cocos2dxTypefaces. get (context, fontName );
Paint. setTypeface (typeFace );
} Catch (Exception e ){
Log. e ("Cocos2dxBitmap ",
"Error to create ttf type face:" + fontName );

/*
* The file may not find, use system font
*/
Paint. setTypeface (Typeface. create (fontName, Typeface. NORMAL ));
}
}
Else {
Paint. setTypeface (Typeface. create (fontName, Typeface. NORMAL ));
}

.......

Return paint;
}
(PS: Typeface class defines the internal types of fonts and fonts. This class is used when the Paint brush is set. For example, textSize, textSkewX, and textScale are used to specify how text is displayed and measured during painting.
In android, Typeface is used to specify the font)

Note that the font must be. ttf.

Usage:
1. Add girl. ttf to the proj. android \ assets folder.
2. Call the corresponding font in the program.
CCSize size = CCDirector: shareddire()-> getWinSize ();
CCLabelTTF * label = CCLabelTTF: create ("girl HelloWorld", "girl. ttf", 24 );
Label-> setPosition (ccp (size. width/2, size. height/2 ));
AddChild (label );
3. If you need to display Chinese characters, you need to convert files containing strings (such as. cpp) to UTF-8 format encoding, otherwise garbled characters will appear

IOS and win32 platforms are not tested. I believe they are similar.

Attached test image:

 


Haha, you can pack the fonts you want in the game.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.