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>
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;
}
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/"
}
I used cufon replacement for devices that didn't support my local font face. I wrote a javascript function to determine whether cufon is required
requiresCufon : function(){
var version = window.navigator.userAgent.match(/Android\s+([\d\.]+)/);
var MINIMUM_OS_FONTFACE = 2.2;
if(typeof version != 'undefined'){
//strip non digits
version = version[0].replace(/[^0-9\.]/g, '');
//if version is less than required for @font-face then cufon
if(parseFloat(version) < MINIMUM_OS_FONTFACE)
return true;
else
return false;
}
else{
return true;
}
},
来源:https://stackoverflow.com/questions/6724653/change-webview-font-using-css-font-file-in-asset-folder-problem