Showing posts with label Custom Font. Show all posts
Showing posts with label Custom Font. Show all posts

Thursday, February 21, 2013

Custom Font on Local Html for Titanium Mobile SDK WebView for Android

While trying to load a locally generated html on the android webview, I noticed that it was not able to render the text content with the custom font face I was using. After some searching, I found out that this issue is not only present on titanium sdk but also from the base android sdk as well (here is the link for the solution on android: Changing Font Face on Android Webview). Using essentially the same approach for the titanium code, here is what I did:

1. Put the font file on the Resource directory of the Titanium project. In here, I am using Airstream.ttf for my custom font face and I placed it in a subfolder named 'fonts' on the Resource folder.

2. Set the css code to use the font face accordingly.
<style type="text/css">
  body {
    font-family:Airstream;
    font-size:20pt;
  }
  @font-face {
     font-family : "Airstream";
     src:url("Airstream.ttf");
  }
</style>

3. On your application code, copy the font file to the directory where your local html (to be rendered on the WebView) will be written. In my code, I just used the default application directory.

1:  var fontFile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory + 'fonts/', 'Airstream.ttf');  
2:  var fontCopy = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'Airstream.ttf');  
3:  if (!fontCopy.exists()) {  
4:       fontFile.copy(Ti.Filesystem.applicationDataDirectory + 'Airstream.ttf');  
5:  }  

4. Write the html file in the same directory as the font file and load it on the webview:

1:  var htmlFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'test.html');  
2:  htmlFile.write(htmlContent);  
3:  if (htmlFile.exists()) {  
4:       webView.setUrl(htmlFile.nativePath);  
5:  }  

Here is what it looks like on the device: