3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React Native でView コンポーネントのキャプチャ画像を取得する

Last updated at Posted at 2020-07-14

はじめに

React Native でUI 要素のキャプチャを取得したいと思ってやり方を調べたのでメモ。
Android については割愛します。

検証環境

  • React Native v0.63.0
  • iOS 13

react-native-view-shot でキャプチャ画像を取得する

あるUI コンポーネントのキャプチャ画像を取得したいとします。

gre/react-native-view-shot: Snapshot a React Native view and save it to an image を使います。

$ npm i react-native-view-shot --save
$ npx pod-install

撮影したい要素を ViewShot コンポーネントでラップし、 capture() でキャプチャを取得します。

import ViewShot from 'react-native-view-shot';

export const YourComponent: React.FC<Props> = (props: Props) => {
  const viewShot = useRef<any>(null);

  const capture = useCallback(() => {
    viewShot.current.capture().then((uri) => {
      console.log(uri);
    });
  }, []);

  return (
    <View style={styles.container}>
        <ViewShot ref={viewShot} options={{format: 'jpg', quality: 0.9}}>
           <View style={styles.targetView} />
           <TouchableOpacity onPress={capture} style={styles.button} />
        </ViewShot>
    </View>
  );
}

@react-native-community/cameraroll で画像をフォトライブラリに保存する

取得したキャプチャ画像をiOS 端末のカメラロールに保存します。

react-native-community/react-native-cameraroll: CameraRoll is a react-native native module that provides access to the local camera roll or photo library. を使います。

$ npm i @react-native-community/cameraroll --save
$ npx pod-install

Info.plist に記述を追加します。

<key>NSPhotoLibraryUsageDescription</key>
<string>YOUR DESCRIPTION</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>YOUR DESCRIPTION</string>

CameraRoll.save でカメラロールに画像を保存します ( CameraRoll.saveToCameraRoll はdeprecated になっていました)。

    viewShot.current.capture().then((uri) => {
      CameraRoll.save(uri);
    });

さいごに

条件によっては上手くキャプチャされないような気が?
複雑なコンポーネントでも使えるのか要検証です。

3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?