Sunday 9 February 2020

Expo camera 3 autofocus

point camera to object, auto focus sharpens view

press snap, camera lose focus and refocus

final picture

import React, { useState, useEffect } from 'react';
import { Camera } from 'expo-camera';
import * as MediaLibrary from 'expo-media-library';
import {
  Container, Header, Title, Content, Footer,
  FooterTab, Button, Left, Right, Body, Icon, Text,
  Accordion, Card, CardItem, Thumbnail, ListItem,
  CheckBox, DatePicker, DeckSwiper, Fab, View,
  Badge, Form, Item, Input, Label, Picker, Textarea,
  Switch, Radio, Spinner, Tab, Tabs, TabHeading,
  ScrollableTab, H1, H2, H3, Drawer,
} from 'native-base';
import {
  Ionicons, MaterialIcons, Foundation,
  MaterialCommunityIcons, Octicons
} from '@expo/vector-icons';
import * as Font from 'expo-font'

export default function App() {
  const [loadfont, setloadfont] = useState(true)
  const [delay, setdelay] = useState(null)
  const [cameraPermission, setcameraPermission] = useState('denied');
  const [storagePermission, setstoragePermission] = useState('denied')
  const [cameraDirection, setcameraDirection] = useState(Camera.Constants.Type.back);
  const [autoFocus, setautoFocus] = useState('on')
  const [whiteBalance, setwhiteBalance] = useState(0)

  const wbOrder = [
    'sunny',
    'cloudy',
    'shadow',
    'fluorescent',
    'incandescent',
    'auto',
  ]

  const wbIcons = [
    'wb-auto',
    'wb-sunny',
    'wb-cloudy',
    'beach-access',
    'wb-iridescent',
    'wb-incandescent',
  ]

  useEffect(async () => {

    const grantCamera = await Camera.requestPermissionsAsync();
    setcameraPermission(grantCamera.status)

    const grantStorage = await MediaLibrary.requestPermissionsAsync()
    setstoragePermission(grantStorage.status)

    await Font.loadAsync({
      Roboto: require("native-base/Fonts/Roboto.ttf"),
      Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf")
    })
    setloadfont(false)

  }, [])

  //bug in software, need to toggle auto focus for some camera to work
  timeout = (sec) => { return new Promise(resolve => setTimeout(resolve, sec)) }

  takePicture = async () => {

    if (this.camera) {
      toggleautoFocus()
      await timeout(100)
      toggleautoFocus()
      await timeout(100)
      toggleautoFocus()
      await timeout(100)
      toggleautoFocus()
      await timeout(1000)

      const { uri } = await this.camera.takePictureAsync();

      await MediaLibrary.saveToLibraryAsync(uri)
        .then(() => {
          alert('image saved!')
        })
        .catch(error => {
          alert('An Error Occurred!')
        });
    }
  }

  togglewhiteBalance = () => {
    whiteBalance < 5 ? setwhiteBalance(whiteBalance + 1) : setwhiteBalance(0)
  }

  toggleautoFocus = () => {
    autoFocus === 'on' ? setautoFocus('off') : setautoFocus('on')
  }

  if (cameraPermission !== 'granted' || storagePermission !== 'granted') {
    return <Text style={{ marginTop: 25 }}>App uses camera and storage</Text>;
  }

  if (loadfont) {
    return <Container style={{ backgroundColor: 'black' }}><Spinner /></Container>
  }

  return (
    <View style={{ flex: 1 }}>
      <Camera style={{ flex: 1 }}
        type={cameraDirection}
        autoFocus={autoFocus}
        whiteBalance={wbOrder[whiteBalance]}
        focusDepth={1}
        ref={ref => { this.camera = ref }}>

        <View style={{
          flex: 1,
          justifyContent: 'space-between',
        }}>
          <View style={{
            justifyContent: 'space-around',
            flexDirection: 'row',
            marginTop: 25
          }} >
            <Button rounded transparent style={{ height: 50 }}
              onPress={() => togglewhiteBalance()}>
              <MaterialIcons name={wbIcons[whiteBalance]} size={40} color="white" />
            </Button>
            <Button rounded transparent style={{ height: 50 }}
              onPress={() => toggleautoFocus()}>
              <Text style={{ color: autoFocus === 'on' ? "white" : "#6b6b6b", fontSize: 25 }}>AF</Text>
            </Button>
          </View>
          <View style={{
            justifyContent: 'center',
            flexDirection: 'row',
            marginBottom: 25,
          }}>
            <Button rounded transparent style={{ height: 80 }}
              onPress={() => { takePicture() }}>
              <Icon name='camera' style={{ fontSize: 60, color: 'white' }} ></Icon>
            </Button>
          </View>
        </View>

      </Camera>
    </View>
  );
}

reference:
https://github.com/expo/expo/issues/706
https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout
https://chuanshuoge2.blogspot.com/2020/02/expo-camera-2-whitebalance.html

No comments:

Post a Comment