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.

krsteeve
  • 1,794
  • 4
  • 19
  • 29
Ihor Bykov
  • 1,843
  • 3
  • 15
  • 22
  • A successful call to `GetStringUTFChars` needs to be followed with `ReleaseStringUTFChars` when you are done with the array. (I don't know what character set/encoding `SkTypeface::CreateFromFile` requires but you are giving it Unicode/modified UTF-8.) – Tom Blodget Jul 09 '13 at 02:40
  • Thanks, but this facts i had known, also i need to delete tes. But my point was how SkTypeface::CreateFromFile(const char path[]) is working, if i gave her path to my font in folder assets(android project), "../assets/fonts/Agora/Agora-Reg.ttf" – Ihor Bykov Jul 09 '13 at 06:03

1 Answers1

2

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;
    }
Ihor Bykov
  • 1,843
  • 3
  • 15
  • 22