React-native-view-shot (컴포넌트 캡쳐)

부가 설명
컴포넌트 뷰를 이미지로 캡쳐
Tags
screenshot

React-native-view-shot

RN의 컴포넌트uri-data로 캡쳐한다.

공식 깃헙

설치 ( RN≥ 0.60 이상 기준)

#패키지 설치 $ yarn add react-native-view-shot #링킹 $ npx pod-install
 

Props 설명 ← 출력형식 png, jpg, data-uri 등 지정가능

Returns a Promise of the image URI.
  • view is a reference to a React Native component.
  • options may include:
    • width / height (number): the width and height of the final image (resized from the View bound. don't provide it if you want the original pixel size).
    • format (string): either png or jpg or webm (Android). Defaults to png.
    • quality (number): the quality. 0.0 - 1.0 (default). (only available on lossy formats like jpg)
    • result (string), the method you want to use to save the snapshot, one of:
      • "tmpfile" (default): save to a temporary file (that will only exist for as long as the app is running).
      • "base64": encode as base64 and returns the raw string. Use only with small images as this may result of lags (the string is sent over the bridge). N.B. This is not a data uri, use data-uri instead.
      • "data-uri": same as base64 but also includes the Data URI scheme header.
        • *****이 옵션으로 data-uri 로 뽑을 수 있음*******
           
    • snapshotContentContainer (bool): if true and when view is a ScrollView, the "content container" height will be evaluated instead of the container height.
    •  

코드사용 예시

마운트 되면셔 바로 캡쳐하기

import ViewShot from "react-native-view-shot"; //마운트 되면서 바로 캡쳐하기 - caputre().then()을 직접 호출하는 경우 class ExampleCaptureOnMountManually extends Component { componentDidMount () { this.refs.viewShot.capture().then(uri => { console.log("do something with ", uri); }); } render() { return ( <ViewShot ref="viewShot" options={{ result:'dara-uri' }}> <Text>...Something to rasterize...</Text> </ViewShot> ); } } //마운트 되면서 바로 캡쳐하기 - 그냥 위의 예시를 좀 더 쉽게 쓸 수 있게 onCapture 함수 만든거임. class ExampleCaptureOnMountSimpler extends Component { onCapture = uri => { console.log("do something with ", uri); } render() { return ( <ViewShot onCapture={this.onCapture} captureMode="mount" options={{result:'dara-uri'}}> <Text>...Something to rasterize...</Text> </ViewShot> ); } }
 

이미지 로딩되기 기다렸다가 캡쳐하기

import ViewShot from "react-native-view-shot"; // waiting an image class ExampleWaitingCapture extends Component { onImageLoad = () => { this.refs.viewShot.capture().then(uri => { console.log("do something with ", uri); }) }; render() { return ( <ViewShot ref="viewShot" options={{result:'dara-uri'}}> <Text>...Something to rasterize...</Text> <Image ... onLoad={this.onImageLoad} /> </ViewShot> ); } }
 

스크롤뷰 화면 캡쳐하기

  • 공식 깃헙을 꼭 읽어보고 쓰자.
import ViewShot from "react-native-view-shot"; // capture ScrollView content class ExampleCaptureScrollViewContent extends Component { onCapture = uri => { console.log("do something with ", uri); } render() { return ( <ScrollView> <ViewShot onCapture={this.onCapture} captureMode="mount" options={{result:'dara-uri'}}> <Text>...The Scroll View Content Goes Here...</Text> </ViewShot> </ScrollView> ); } }
 

함수형 컴포넌트에서 사용하기

함수형에선 string 형태로 ref 이름 지정할 수도 없고, 애초에 refs도 없다.
useRef() hook 을 써야함.

잘 돌아가는 예시 (png 파일로 출력)

import React, { Component, useEffect, useRef } from 'react' import { Text, Image, ImageBackground, View, StyleSheet } from 'react-native' import { Button } from 'react-native-paper'; import ViewShot from "react-native-view-shot"; import { useSelector } from 'react-redux' export default function TestCustomMark() { const { locations } = useSelector((state) => ({ locations: state.locations })) const viewShot = useRef(); const focusOnHandler = () => { viewShot.current.capture().then((uri) => console.log(uri)); }; return ( <View style={{flex:0}}> <Button onPress={focusOnHandler}> Capture </Button> <ViewShot ref={viewShot} options={{ format: "png" }} style={{ borderWidth: 1, alignItems: 'center', height: 105, width: 140 }}> <ImageBackground source={require("../Assets/pimMarker.png")} style={{ width: 130, height: 100 }}> <View style={{ flex: 1, alignItems: 'center' }}> <Text style={{ paddingTop: 5, paddingLeft: 10, fontSize: 50 }}> { //%1f 형태로 나타냄 locations[3].payPerHour % 1000 == 0 ? locations[3].payPerHour / 1000 + ".0" : locations[3].payPerHour / 1000 } </Text> </View> </ImageBackground> </ViewShot> </View> ); }
 
CAPTURE 버튼 클릭 시 렌더링된 컴포넌트를 캡쳐하고 tmp 폴더에 저장한다. (자동삭제됨)
notion image
notion image
notion image