Giter VIP home page Giter VIP logo

reime005 / react-native-camera-hooks Goto Github PK

View Code? Open in Web Editor NEW
109.0 4.0 16.0 3.08 MB

React Hooks and API wrapper for the react-native-camera module. GitHub Actions CI/CD + Automatic Release

License: MIT License

JavaScript 37.48% TypeScript 15.38% Java 22.54% Objective-C 3.45% Starlark 0.86% Ruby 2.35% CMake 0.41% C++ 10.46% Objective-C++ 6.37% Shell 0.69%
react-native hooks react-native-camera javascript typescript github-actions cicd github-releases hacktoberfest

react-native-camera-hooks's Introduction

 

Hooks for React Native Camera

 

React Native Camera Hooks provides you with functionality to use the React Native Camera API with Functional Components.

 

npm GitHub CircleCI Deploy

import { View, TouchableOpacity, TouchableWithoutFeedback } from 'react-native';
import { RNCamera } from 'react-native-camera';
import { useCamera } from 'react-native-camera-hooks';

const FunctionalComponentExample = ({ initialProps }) => {
  const [
    { cameraRef, type, ratio, autoFocus, autoFocusPoint, isRecording },
    {
      toggleFacing,
      touchToFocus,
      textRecognized,
      facesDetected,
      recordVideo,
      setIsRecording,
    },
  ] = useCamera(initialProps);

  return (
    <View style={{ flex: 1 }}>
      <RNCamera
        ref={cameraRef}
        autoFocusPointOfInterest={autoFocusPoint.normalized}
        type={type}
        ratio={ratio}
        style={{ flex: 1 }}
        autoFocus={autoFocus}
        onTextRecognized={textRecognized}
        onFacesDetected={facesDetected}
      />

      <TouchableWithoutFeedback
        style={{
          flex: 1,
        }}
        onPress={touchToFocus}
      />

      <TouchableOpacity
        testID="button"
        onPress={toggleFacing}
        style={{ width: '100%', height: 45 }}>
        {type}
      </TouchableOpacity>

      {!isRecording && (
        <TouchableOpacity
          onPress={async () => {
            try {
              setIsRecording(true);
              const data = await recordVideo();
              console.warn(data);
            } catch (error) {
              console.warn(error);
            } finally {
              setIsRecording(false);
            }
          }}
          style={{ width: '100%', height: 45 }}
        />
      )}
    </View>
  );
};

Features

  • React Hooks Support: Use React Native Camera with Functional Components
  • Wrapper around the Camera API, that makes the usage easier
  • TypeScript support

Constants are defined in constants and initalState.

Function Description
useCamera(initialState) Includes all camera hooks described below. See also the example above
useZoom(state) Zoom feature. Includes zoom, setZoom, zoomIn (increment by 0.01) and zoomOut (decrement by 0.1)
useToggleFacing(state, modes) Toggles between two values (front and back side of the camera). Includes type, toggleFacing.
useAutoFocus(state, modes) Toggles between two values (focus on or off). Includes autoFocus and toggleAutoFocus.
useWhiteBalance(state) Toggles between white balance values. Includes whiteBalance, toggleWB and setWhiteBalance.
useFlash(state) Toggles between flash modes. Includes flash, toggleFlash and setFlash.
useAutoFocusTouch(state) Touch to focus feature. Includes autoFocusPoint, touchToFocus (callback to be used in onPress for example) and setAutoFocusPoint.
useTextRecognition(state) Text recognition feature. Includes textBlocks, setTextblocks and textRecognized (callback).
useFaceDetection(state) Face detection feature. Includes faces, setFaces and facesDetected (callback).
useBarcodeDetection(state) Barcode detection feature. Includes barcodes, setBarcodes and barcodeRecognized (callback).
takePicture({ cameraRef }, options) Function to take a picture. Returns a Promise with the result. defaultPictureTakeOptions can also be imported from the same file.
recordVideo({ cameraRef }, options) Function to record a video. Returns a Promise with the result. defaultVideoRecordOptions can also be imported from the same file.
stopRecording({ cameraRef }) Function to stop recording. Returns a Promise.
pausePreview({ cameraRef }) Function to pause the camera preview. Returns a Promise with the result as a boolean.
resumePreview({ cameraRef }) Function to resume the camera preview. Returns a Promise with the result as a boolean.

 


Installation

To install react-native-camera-hooks, do either

npm install --save react-native-camera-hooks

or

yarn add react-native-camera-hooks

Note that this requires a react-native version > 0.59 which supports React Hooks. Also, react-native-camera has to be installed.

 


TODO

  • Improve TypeScript support

react-native-camera-hooks's People

Contributors

brentvatne avatar bwnstck avatar dependabot[bot] avatar geuntabuwono avatar guicavi avatar patlm avatar reime005 avatar semantic-release-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-native-camera-hooks's Issues

Question: Barcode scanning

Apologies if this is in the wrong place,

I am wrestling with getting this barcode scanning to work but with no success - any chance anyone can help me determine what I am doing wrong? All I am trying to do is console.log the barcodes scanned but I'm getting no response when pointing the camera at any QR code.

many thanks in advance for any help
Screenshot 2021-05-19 132116

Alex

error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

Some typescript files seems to be picked up by tsc compiler:

node_modules/react-native-camera-hooks/src/recordVideo.ts:33:4 - error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

33 ): Promise<RecordResponse> => {
      ~~~~~~~~~~~~~~~~~~~~~~~

node_modules/react-native-camera-hooks/src/takePicture.ts:39:4 - error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

39 ): Promise<TakePictureResponse> => {
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It seems that the entry point is not correctly exposing the correct file:
"main": "src/index.js"
should probably be
"main": "dist/react-native-camera-hooks.js"

use with expo-camera

Hi,

Is it possible to use this with expo-camera rather than react-native-camera?

Thanks,

Bill

Calling stopRecording function does not end the recording

When calling the stopRecording function, the recording still continues until the maxDuration is reached. This is because the stopRecording function was missing the cameraRef attribute when being called in the hooks.js file.

Should be linked to PR: #65

Type issues with `CameraOptions` / initial props

Looks like CameraOptions isn't using the types provided by react-native-camera, which is causing the compiler to complain when passing initial props to useCamera. You should be able to use the types provided by react-native-camera to build the hook's options/params.

https://joeysharesthings.com/EPh8G3

TypeError: undefined is not an object (evaluating '_a.cameraRef') when using stopRecording()

I am encountering this error whenever I try to use stopRecording() from the useCamera hook.

Possible Unhandled Promise Rejection (id: 11):
TypeError: undefined is not an object (evaluating '_a.cameraRef')
stopRecording@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:270079:23
handlePressRecord$
tryCatch@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25804:23
invoke@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25977:32
tryCatch@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25804:23
invoke@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25877:30
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25907:19
tryCallTwo@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27895:9
doResolve@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:28059:25
Promise@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27918:14
callInvokeWithMethodAndArg@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25906:33
enqueue@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25911:157
async@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25928:69
etc etc...

My RNCamera's ref is set to the cameraRef given by the hook but I don't know why it doesn't work.
The other hooks work but if I can't stop recording I cannot save videos...
I have not seen this function used in any of the demos so maybe it's just not finished.

Here's a snippet of my code:

//other imports blablabla
import { RNCamera } from "react-native-camera";
import { useCamera } from "react-native-camera-hooks";

function InternalRecordingOverlay({
  isVisible,
  setVisible,
  project,
  userObject,
  clipFunctions,
}) {
  const [UIrecording, setUIRecording] = useState(false);
  const [locked, setLocked] = useState(false);
  const [phantomMode, setPhantomMode] = useState(false);
  const isFocused = useIsFocused();
  const currentTheme = useTheme();
  const colors = currentTheme.colors;
  const [videoQuality, setVideoQuality] = useState(
    RNCamera.Constants.VideoQuality["720p"]
  );
  const [orientation, setOrientation] = useState(
    RNCamera.Constants.Orientation.auto
  );

  const [
    {
      cameraRef,
      type,
      ratio,
      autoFocus,
      autoFocusPoint,
      isRecording,
      drawFocusRingPosition,
      whiteBalance,
      zoom,
      flash,
    },
    {
      toggleFacing,
      touchToFocus,
      toggleAutoFocus,
      takePicture,
      setWhiteBalance,
      recordVideo,
      setIsRecording,
      stopRecording,
      setAutoFocusPoint,
      setZoom,
      setFlash,
    },
  ] = useCamera({
    type: RNCamera.Constants.Type.back,
    zoom: 0,
    flash: RNCamera.Constants.FlashMode.off,
  });
//some functions were left out but they are outside the scope of the problem

const handlePressRecord = async () => {
    //ADD DOUBLETAP PROTECTION
    if (!UIrecording) {
      //Start recording
      setUIRecording(true);
        try {
          setIsRecording(true);
          const vidInfo = await recordVideo({
            quality: videoQuality,
            orientation: orientation,
          });
          recordStart = dayjs();
          currentVideo = {
            isPhantom: false,
            vidInfo: vidInfo,
            timeOfStart: recordStart,
          };
          console.log(JSON.stringify(currentVideo));
        } catch (error) {
          console.warn(error);
        } finally {
          setIsRecording(false);
        }
    } else {
      //Stop recording
      await stopRecording();
      setUIRecording(false);
      //Cliprecord Stop
      console.log("This never gets reached");
      let archiveCurrent = currentVideo;

        mediaLibUtils
          .saveFileInProjectAlbum(archiveCurrent.vidInfo.uri, project.name)
          .then(() => {
            FileSystem.deleteAsync(archiveCurrent.vidInfo.uri, {
              idempotent: true,
            });
          });
    }
  };

  if (!isFocused || !isVisible /* || hasPermission === null */) {
    return null;
  }

 return (
    <Overlay
      fullScreen={true}
      onDismiss={() => setVisible(false)}
      overlayStyle={styles.container}
      statusBarTranslucent
      isVisible={isVisible}
    >
      <>
        <RNCamera
          ref={cameraRef}
          style={[styles.camera, { height: (D.width * 16) / 9 }]}
          ratio="16:9"
          useNativeZoom={true}
          zoom={zoom}
          //trackingEnabled={true}
          autoFocus={autoFocus}
          autoFocusPointOfInterest={autoFocusPoint.normalized}
          onTap={(pos) => touchAndFocus(pos)}
          type={type}
          flashMode={flash}
          androidCameraPermissionOptions={{
            title: "Permission to use camera",
            message: "We need your permission to use your camera",
            buttonPositive: "Ok",
            buttonNegative: "Cancel",
          }}
          androidRecordAudioPermissionOptions={{
            title: "Permission to use audio recording",
            message: "We need your permission to use your audio",
            buttonPositive: "Ok",
            buttonNegative: "Cancel",
          }}
        >
          <View
            pointerEvents="none"
            style={{
              position: "absolute",
              top: autoFocusPoint.drawRectPosition.x - 40,
              right: autoFocusPoint.drawRectPosition.y - 40,
              height: 80,
              width: 80,
              backgroundColor: colors.transparent,
              borderWidth: 1,
              borderColor: colors.primary,
            }}
          />
<View style={styles.bottomContainer}>
            <TouchableOpacity
              onPress={handlePressRecord}
              disabled={locked}
              style={[
                styles.recButton,
                {
                  backgroundColor: colors.white,
                },
              ]}
            >
              {UIrecording ? (
                <View
                  style={{
                    backgroundColor: colors.dark,
                    width: 35,
                    height: 35,
                  }}
                />
              ) : (
                <View
                  style={{
                    backgroundColor: colors.brightred,
                    width: 30,
                    height: 30,
                    borderRadius: 15,
                  }}
                />
              )}
            </TouchableOpacity>
      </>
    </Overlay>
  );
} //This was vastly abridged

If someone had a solution to stop recording that would be great, even if I have to bodge together the library I need to get this working.

EDIT: I noticed that if I switch cameras during the recording or if I close the overlay the recording will stop and the videos details are the following:

{"uri":"file:///data/user/0/com.appname.appname2/cache/Camera/a5c97a4e-e6b6-42f4-ac0a-21003df446ed.mp4","deviceOrientation":1,"videoOrientation":1,"isRecordingInterrupted":false}

For obvious reasons using such functions to stop recording is not a solution

Thanks for reading

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.