LoginSignup
1
1

More than 3 years have passed since last update.

React Nativeで文字幅を取得する

Last updated at Posted at 2021-05-13

Webなら文字幅は 1ch で取得できるが、React Nativeでは px % での指定しかできないので、要素の幅を取得することで擬似的に取得することにした。

ポイント

  • Textの onLayout を使って要素の幅を取得する。
  • padding, margin, borderなどの余白は0にする
  • 1文字の幅を取得したい場合、文字数で割る

注意点

  • 等幅フォントでなければ、文字数で割っても正確な幅にはならない

  • 画面の解像度に合わない(切りの悪い)px幅の場合、最も近いピクセルに合わせられてしまうため、表示と合わない

例)

計算値 画面上の表示幅
10.75px 10.5px
9.8px 10px
import React, {Component} from 'react';
import { Text, View, StyleSheet } from 'react-native';

type Props = {}
type State = {
  charWidth: number
}

const text = 'A'

export default class App extends Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = {
      charWidth: 0,
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.textBox}>
          <Text
            onLayout={(e) => {
              this.setState({
                charWidth: e.nativeEvent.layout.width,
              })
            }}
            style={styles.char}
          >
            {text}
          </Text>
        </View>
        <Text>Size: {this.state.charWidth}px</Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  textBox: {
    display: 'flex',
    flexDirection: 'row',
  },
  char: {
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    backgroundColor: '#eee',
    padding: 0,
    margin: 0,
    borderWidth: 0,
  },
});

Demo: https://snack.expo.io/TRAFtndhu

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1