Android:
1. Add the following method to ccimage:
// The header file declaration is omitted.
Cocos2d: ccsize ccimage: getstringsize (const char * Text, const char * pfontname, int nsize)
{
Jnimethodinfo minfo;
If (! Jnihelper: getstaticmethodinfo (minfo, "org/cocos2dx/lib/cocos2dxbitmap", "getfontsize ",
"(Ljava/lang/string; I) [I "))
{
Cclog ("getstringsize % S % d: error to get methodinfo", _ file __, _ line __);
Return ccsizemake (nsize, nsize );
}
Jstring jmsg1 = minfo. env-> newstringutf (text );
Jstring jmsg2 = minfo. env-> newstringutf (pfontname );
Jint size = nsize;
Jintarray array = (jintarray) minfo. env-> callstaticobjectmethod (minfo. classid, minfo. methodid, jmsg1, jmsg2, size );
Jsize Len = minfo. env-> getarraylength (array );
Jint * Body = minfo. env-> getintarrayelements (array, 0 );
If (Body = NULL ){
Cclog ("body % S % d: error to get methodinfo", _ file __, _ line __);
Return ccsizemake (nsize, nsize );
}
Int width = body [0];
Int Height = body [1];
// The following cleanup operations are required. Otherwise, referencetable overflow (max = 512) will be reported)
Minfo. env-> releaseintarrayelements (array, body, 0 );
Minfo. env-> deletelocalref (jmsg1 );
Minfo. env-> deletelocalref (jmsg2 );
Minfo. env-> deletelocalref (array );
Return ccsizemake (width, height );
}
2. Add the following content to the cocos2dxbitmap class:
Static string tempfontname = "";
Static int tempfontsize = 0;
Private Static paint tmppaint;
Public static int [] getfontsize (string text, final string pfontname, final int pfontsize ){
If (tmppaint = NULL | tempfontsize! = Pfontsize |! Tempfontname. Equals (pfontname )){
Log. I ("cocos2d-x-android", "pfontname =" + pfontname + "pfontsize =" + pfontsize );
Tmppaint = cocos2dxbitmap. newpaint (pfontname, pfontsize, horizontalalign_left );
Tempfontname = pfontname;
Tempfontsize = pfontsize;
}
Int width = (INT) tmppaint. measuretext (text );
Final fontmetricsint fm = tmppaint. getfontmetricsint ();
Int Height = (INT) math. Ceil (FM. Bottom-FM. Top) + 2;
Return new int [] {width, height };
}
IOS:
Ccsize ccimage: getstringsize (const char * Text, const char * pfontname, int nsize)
{
Nsstring * STR = [nsstring stringwithuf8string: text];
Nsstring * fntname = [nsstring stringwithuf8string: pfontname];
Cgsize dim, constrainsize;
Id font = [uifont fontwithname: fntname size: nsize];
If (font)
{
Dim = _ calculatestringsize (STR, Font, & constrainsize );
}
Else
{
If (! Font)
{
Font = [uifont systemfontofsize: nsize];
}
If (font)
{
Dim = _ calculatestringsize (STR, Font, & constrainsize );
}
}
Return ccsizemake (dim. Width, Dim. Height );
}