LoginSignup
0

More than 1 year has passed since last update.

React Nativeで、ImageをView内ピッタリに収める方法

Last updated at Posted at 2021-10-13

React Nativeで、画像のアスペクト比を維持しつつ、画像をView内にピッタリ、余白なしに収める方法を紹介します。

環境

  • React Native: 0.64

概要

  1. onLoadを使い、画像のwidthとheightを取得し、widthとheightからアスペクト比を計算
  2. 計算したアスペクト比をImageコンポーネントのstyleprops内のaspectRatioプロパティに当てる

やり方

import React, { useCallback, useState } from 'react-native'
import { Image, View, ImagePropsBase } from 'react-native'
(中略)

const Hoge: FC = () => {
  const [imageAspectRatio, setImageAspectRatio] = React.useState(1)

  const calculateAspectRatio = useCallback<ImagePropsBase['onLoad']>(
    ({
      nativeEvent: {
        source: { width, height },
      },
    }) =>
      setImageAspectRatio(width / height),
    [],
  );

  return (
    <View style={{ flex: 1 }}>
      <Image
        onLoad={calculateAspectRatio}
        resizeMode="contain"
        source={{ uri: 'http://example.com/hoge.jpg' }}
        style={{
          width: '100%' // 適宜指定したい値に変えてください。
          aspectRatio: imageAspectRatio
        }}
      />
    </View>
  )
}

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
0