0

I'm new to Android, and I am wondering how to create Typeface from assets

I have my .ttf file in my Android application in the assets folder.

I'm using native code to create typeface:

class Test
{
public:
    Test(){};
    Test(const char* path);
    bool getHasFont(){ return hasFont;}
    ~Test(){}


private:
   SkPaint paint;
   SkTypeface* typeface;
   bool hasFont;
};

Test::Test(const char* path)
{

LOGI(path);
typeface = SkTypeface::CreateFromFile(path);        
if(typeface != NULL)
    hasFont = true;
else
    hasFont = false;
}



JNIEXPORT jboolean JNICALL Java_com_example_Test_NativeSkia_getHelloFromNative(JNIEnv *env,
        jclass clazz, jstring path) {

const char *nativeString = env->GetStringUTFChars(path, 0); 

Test* tes = new Test(nativeString);
return tes->getHasFont();
}
}

In Android application I'm calling:

boolean isWorking = NativeSkia.getTestFromNative("../assets/fonts/Agora/Agora-Reg.ttf"); 

Its returning false;

If I create the folder on the sd card, in device, and put all my fonts there:

boolean isWorking = NativeSkia.getTestFromNative("/mnt/sdcard/fonts/Agora/Agora-Reg.ttf");

It works fine, but I need to have my fonts in the assets folder.

4

1 回答 1

2

文件路径不正确,在这种情况下您不能使用相对路径。我不需要使用 Android NDK 的asset_manager.h 和asset_manager_jni.h 来获取要传递给Skia 的文件描述符。

JNIEXPORT jboolean JNICALL Java_com_example_KernMe_NativeSkia_getHelloFromNative(JNIEnv *env,
        jclass clazz, jobject assetManager, jstring path) {

    AAssetManager *mgr = AAssetManager_fromJava(env, assetManager);
    if (mgr == NULL) 
       return false;
    const char *nativeString = env->GetStringUTFChars(path, 0); 


    AAsset* asset = AAssetManager_open(mgr, nativeString, AASSET_MODE_BUFFER);
    if (NULL == asset)
        return false;

    SkStream* stream = new AssetStream(asset, true);
    SkTypeface* face = SkTypeface::CreateFromStream(stream);
    if(face == NULL)
        return false;


    env->ReleaseStringUTFChars(path, nativeString);
    AAsset_close(asset);

    return true;
    }
于 2013-07-11T11:26:40.213 回答