react-native-webview,使用自定义字体

317 阅读1分钟

创建一个为WebView生成html的函数

export const generateHtml = (fontFamily='MicrosoftYaHei',fileFormat='ttf') => {
  const fileName = Platform.select({ 
      ios: `${fontFamily}.${fileFormat}`, 
      android: `file:///android_asset/fonts/${fontFamily}.${fileFormat}` 
  });
  return (
    `
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
          <style media="screen" type="text/css">
            @font-face { 
              font-family: '${fontFamily}'; 
              src: url('${fileName}') format('${ fileFormat === "ttf" ? "truetype" : "opentype" }'); }
            html, body {
              font-family: '${fontFamily}';
            }
          </style>
      </head>
      <body>
        ${content}
      </body>
    `
  )
}

使用

import { WebView } from 'react-native-webview'
const html = generateHtml()
<WebView
    originWhitelist={['*']} 
    source={{ html, baseUrl: ''}} //baseUrl适用于iOS,安卓不需要
/>

需要注意的点是,fontFamily的值不一定是字体文件的文件名称。如果有mac电脑,通过字体册软件打开,可以查看到该字体文件正确的fontFamily值。
关于自定义字体,看这篇:React Native 自定义字体

另一个方案是:使用base64
转base64的工具 transfonter.org
注意的点是,打开base64开关,默认是关闭的 image.png

使用的时候,可以直接复制粘贴transfonter生成的css代码
举例:
@font-face {
font-family: 'Apple Chancery';
src: url(data:application/font-woff;charset=utf-8;base64,YourFontInBase64Format) format('woff');
font-weight: normal;
font-style: normal;
}