Question

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.

Was it helpful?

Solution

File path is not correct you can't use a relative path in this case. I needt to use the Android NDK asset_manager.h and asset_manager_jni.h to get a file descriptor to pass into 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;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top