Skip to content

Support for Custom Fonts #85

@antonlopez

Description

@antonlopez

I am trying to add a custom font to the canvas and it does not work, the custom font works when I use it on a Text component.

issue

you can run it from here:
https://snack.expo.io/@antonlopez/custom-fonts

and here is my code:

import React from 'react';
import { StyleSheet, Text, View, Dimensions } from 'react-native';
import { Font } from 'expo';
import Canvas, {Image as CanvasImage} from 'react-native-canvas';
const SCREEN_HEIGHT = Dimensions.get('window').height;
const SCREEN_WIDTH = Dimensions.get('window').width;



export default class App extends React.Component {
  constructor(props) {
  super(props);
  this.state = {
    loadingFont: true
  };
}

async componentWillMount() {
    await Font.loadAsync({
     'Biysk': require('./assets/fonts/Biysk.ttf'),
    });
    this.setState({ loadingFont: false });
  }

handleCanvas = (canvas) => {
  
   const image = new CanvasImage(canvas);
   canvas.width = SCREEN_WIDTH;
   canvas.height = SCREEN_HEIGHT + 20;

   const ctx = canvas.getContext('2d');

   image.src = 'https://image.freepik.com/free-vector/unicorn-background-design_1324-79.jpg';
   image.addEventListener('load', () => {
     ctx.drawImage(image, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
     ctx.fillStyle = 'purple';
     ctx.textAlign="center";
     const customFont = `${this.state.loadingFont ? 'Verdana': 'Biysk'}`;
     console.log(customFont) // verified that the custom font is loaded
     ctx.font = `44px ${customFont}`;
     ctx.fillText('This is a test',200,80);
   });
  }


  render() {
    return (
      <View style={styles.container}>
        <Canvas ref={this.handleCanvas}/>
        <Text style={{ fontFamily: `${this.state.loadingFont ?  '': 'Biysk'}`}}>
            Custom Font style works
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  }
});

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions