Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change WebView font using CSS; font file in asset folder. (problem)

I want to change WebView font. There are 2 files in "assets" folder. They are:

assets/fonts/DejaVuSans.ttf and

assets/css/result.css

I searched some answers on StackOverflow and find out a solution but it doesn't work. The result.css loads DejaVuSans.ttf using @font-face directive. Then it is included in < link > tag of data which is passed to WebView::loadDataWithBaseURL (The code is below). The problem is CSS styles works (the text is red) but the font doesn't. Square characters appears when I show phonetic symbols (/'pə:sn/).

String resultText = "<html><head>";
resultText += "<link href=\"css/result.css\"" + " rel=\"stylesheet\" type=\"text/css\" />";
resultText += "<style>" + "@font-face { font-family: \"DejaVuSans\"; " + "" +
"src: url('file:///android_asset/fonts/DejaVuSans.ttf'); }</style>";
resultText += "</head>";
resultText += "<body><p>" + text + "</p>" + "</body></html>";
resultView.loadDataWithBaseURL("file:///android_asset/", resultText, "text/html", "utf-8", null);

result.css:

@font-face { 
    font-family: "DejaVuSans"; 
    /*src: url('fonts/DejaVuSans.ttf'); also not work*/ 
    src: url('file:///android_asset/fonts/DejaVuSans.ttf');
}

body {
    color: red;
}

The System.out.println(resultText) is:

   <html><head><link href="css/result.css" rel="stylesheet" type="text/css" /><style>@font-face { font-family: "DejaVuSans"; src: url('file:///android_asset/fonts/DejaVuSans.ttf'); }</style></head><body><p>person /'pə:sn/</p></body></html>
like image 345
emeraldhieu Avatar asked Jul 17 '11 15:07

emeraldhieu


2 Answers

It was solved. I didn't add "font-family" to body selector and font url must be file:///android_asset/fonts/DejaVuSans.ttf".

@font-face { 
    font-family: 'DejaVuSans'; 
    /* src: url('DejaVuSans.ttf'); This doesn't work */
    /* src: url('fonts/DejaVuSans.ttf'); Neither is this */
    src: url('file:///android_asset/fonts/DejaVuSans.ttf'); /* but this does */
}

body {
    font-family: 'DejaVuSans';
    color: red;
}
like image 135
emeraldhieu Avatar answered Oct 02 '22 17:10

emeraldhieu


Known bug on 2.0 and 2.1 :

http://code.google.com/p/android/issues/detail?id=4448

For 2.2 :

@font-face {
    font-family: 'FontName';
    src: url('filefont.ttf'); // with no "fonts/"
}
like image 45
ChristopheCVB Avatar answered Oct 02 '22 18:10

ChristopheCVB