首页 > 代码库 > cocos2dx获得字体的宽高

cocos2dx获得字体的宽高

Android:

1、在CCImage中添加下面的方法:

//头文件声明略。

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;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];

  //以下的清理工作必不可少 否则会报 ReferenceTable overflow (max=512)

    minfo.env->ReleaseIntArrayElements(array, body, 0);

    minfo.env->DeleteLocalRef(jmsg1);

    minfo.env->DeleteLocalRef(jmsg2);

    minfo.env->DeleteLocalRef(array);

    return CCSizeMake(width, height);

}

2、在Cocos2dxBitmap类中添加下面的内容:

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 stringWithUTF8String:text];

    NSString * fntName      = [NSString stringWithUTF8String: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);

}