Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

android - Using custom fonts in React native Webview

I'm using custom fonts in my entire React native application. I have linked them using react-native link command. They work everywhere except inside the Webview component of Android. It works properly in 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>
    )
  }
}

I have tried creating a font-face inside the webview css with url("file:///android_assets/fonts/Lohit-Gujarati"). It doesn't work. Importing google fonts css works. What is the right way to use local custom fonts in React native Android Webview?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Creating a font-face inside the webview css with url("file:///android_asset/fonts/Lohit-Gujarati") works if baseUrl is set on WebView:

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

I'm not sure why it doesn't work without baseUrl, but I think it can be because RN uses a different method to load the WebView when baseUrl is missing:

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...