Change WebView font using CSS; font file in the resource folder. (Problem)

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

assets / fonts / DejaVuSans.ttf and

assets / CSS / result.css

I searched for some answers on StackOverflow and figured out a solution, but it does not work. Result .css loads DejaVuSans.ttf using the @ font-face directive. Then it is included in the <link> data tag, which is passed to WebView :: loadDataWithBaseURL (code below). The problem is with CSS styles (text red), but the font is not . Square characters appear when I show phonetic characters (/ '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; } 

System.out.println (resultText):

  <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> 
+6
source share
3 answers

It was agreed. I did not add "font-family" to the body selector, and the url font should be a 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; } 
+16
source

Known bug 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/" } 
+4
source

I used cufon replacement for devices that did not support my local font. I wrote a javascript function to determine if 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; } }, 
0
source

Source: https://habr.com/ru/post/892941/


All Articles