android - 在 React native Webview 中使用自定义字体

标签 android css webview fonts react-native

我在我的整个 React native 应用程序中使用自定义字体。我已经使用 react-native link 命令链接了它们。除了 Android 的 Webview 组件之外,它们在任何地方都有效。它在 iOS Webview 中正常工作。

import React, { Component } from "react"
import { View, StyleSheet, Text, WebView, ScrollView, Image } from "react-native"
import HTMLView from "react-native-htmlview"

export class PostDetailPage extends Component {

  static navigationOptions = {
    title: ({ state }) => state.params.post.title,
    header: {
      style: {
        backgroundColor: '#FF9800',
      },
      titleStyle: {
        color: 'white',
        fontFamily: "Ekatra",
        fontWeight: "normal"
      },
      tintColor: 'white'
    }
  }

  constructor(props) {
    super(props)
  }

  render() {
    const post = this.props.navigation.state.params.post
    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <style type="text/css">
          body {
            font-family: Lohit-Gujarati;
            font-size: 1.25rem;
            color: black;
            padding: 0px 10px 10px 10px;
          }

          p {
            text-align: justify;
          }
        </style>
      </head>
      <body>
        ${post.content}
      </body>
      </html>
    `
    return (
      <View style={{ flex: 1, overflow: "visible" }}>
        <Image source={{ uri: post.featured_image }} style={{ height: 150 }} />
        <WebView
          source={{html}}
          style={{flex: 1}}
          />
      </View>
    )
  }
}

我尝试使用 url("file:///android_assets/fonts/Lohit-Gujarati") 在 webview css 中创建字体。它不起作用。导入谷歌字体 css 有效。在 React 原生 Android Webview 中使用本地自定义字体的正确方法是什么?

最佳答案

如果在 WebView 上设置了 baseUrl,则可以使用 url("file:///android_asset/fonts/Lohit-Gujarati") 在 webview css 中创建字体:

<WebView
  source={{html, baseUrl: 'someUrl'}}
  style={{flex: 1}}
/>

我不确定为什么没有 baseUrl 就不能工作,但我认为这可能是因为 RN 在缺少 baseUrl 时使用不同的方法加载 WebView:

if (source.hasKey("baseUrl")) {
  view.loadDataWithBaseURL(
      source.getString("baseUrl"), html, HTML_MIME_TYPE, HTML_ENCODING, null);
} else {
  view.loadData(html, HTML_MIME_TYPE, HTML_ENCODING);
}

关于android - 在 React native Webview 中使用自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42943384/

相关文章:

android - 英特尔 x86 仿真器加速器(HAXM 安装程序)修订版 6.0.5 显示与 Windows 不兼容

java - Picasso 无法加载图像但没有提供错误消息?

javascript - css3 或 Javascript 中的页面过渡幻灯片

html - 垂直 Bootstrap 导航栏按钮未对齐

android - 使用 android webview 在浏览器中打开外部链接

android - 无法将大图像加载到 web View android

java - 无法使用字符串作为选项卡名称

android - 无法在 MapView 下方设置按钮

CSS 媒体查询和 Firefox 的滚动条宽度

java - 如何在 WebView 中禁用软键盘