The front-facing camera lacks both auto focus and manual focus capabilities

Current Issue

While using react-native-camera on iPads/iPhones, the front-facing camera does not focus properly when scanning barcodes like Code39, Code128, or QR codes. The rear camera works fine, but the front camera fails to focus on the barcode or anything in close proximity.

I have only tested this on iOS and haven't found any solutions to make the front camera focus correctly.

Even if I hold a barcode up to the camera with a gap at the bottom, it still won't attempt to focus on the code and instead stays focused on objects in the background.

I've posted an issue here on GitHub, but wanted to see if anyone else has encountered this problem and found a workaround.

Expected Outcome

I anticipated the camera to recognize the barcode as the main subject, focus on it, read the code, and trigger the onBarCodeRead function accordingly.

Attempted Solutions

  • Disabled autoFocus, didn't work as expected.
  • Tried setting focusDepth manually, no improvement.
  • Set autoFocusPointOfInterest to center of screen.
  • Adjusted the zoom level incrementally.
  • Used onGoogleVisionBarcodesDetected for Android fix, no success.
  • Updated [email protected]
  • Switched to master branch at
    react-native-camera@git+https://[email protected]/react-native-community/react-native-camera.git

Steps to Reproduce

  • Create a new react-native project.
  • Install react-native-camera.
  • Set
    type={RNCamera.Constants.Type.front}
    to use the front camera.
  • Ensure
    autoFocus={RNCamera.Constants.AutoFocus.on}
    .
  • Implement
    onBarCodeRead={() => alert('barcode found')}
    .
  • Try to scan a Code39 / Code128 barcode from an online generator.
  • The camera won't focus on the barcode and will remain focused on the background instead.

Software & Versions Used

  • iOS: 12.1.4
  • react-native-camera: ^2.1.1 / 2.6.0
  • react-native: 0.57.7
  • react: 16.6.1

Code Snippet

The camera is rendered within a react-native-modal. Here's the relevant code:

<RNCamera 
  style={styles.camera}
  type={RNCamera.Constants.Type.front}
  flashMode={RNCamera.Constants.FlashMode.off}
  autoFocus={RNCamera.Constants.AutoFocus.on}
  captureAudio={false}
  onBarCodeRead={(barcode) => {
    if (this.state.isModalVisible) {
      this.setState({
        isModalVisible : false
      }, () => this.captureQR(barcode.data));
    }
}}>

Relevant Package Code

A relevant piece of code can be found in RNCamera.m at method updateFocusDepth.

- (void)updateFocusDepth
{
    AVCaptureDevice *device = [self.videoCaptureDeviceInput device];
    NSError *error = nil;

    if (device == nil || self.autoFocus < 0 || device.focusMode != RNCameraAutoFocusOff || device.position == RNCameraTypeFront) {
        return;
    }

    if (![device respondsToSelector:@selector(isLockingFocusWithCustomLensPositionSupported)] || ![device isLockingFocusWithCustomLensPositionSupported]) {
        RCTLogWarn(@"%s: Setting focusDepth isn't supported for this camera device", __func__);
        return;
    }

    if (![device lockForConfiguration:&error]) {
        if (error) {
            RCTLogError(@"%s: %@", __func__, error);
        }
        return;
    }

    __weak __typeof__(device) weakDevice = device;
    [device setFocusModeLockedWithLensPosition:self.focusDepth completionHandler:^(CMTime syncTime) {
        [weakDevice unlockForConfiguration];
    }];
}

In particular, the section where it checks if

device.position == RNCameraTypeFront
and returns under certain conditions caught my attention.

Answer №1

When working with IOS, it is important to understand the three different Focus Modes. Specifically, utilizing

AVCaptureFocusModeContinuousAutoFocus
is essential.

AVCaptureFocusModeContinuousAutoFocus: This mode allows the camera to continuously autofocus as needed.

To determine if a device supports a specific focus mode, you can use the isFocusModeSupported method and then set the mode using the focusMode property.

Within the context of react-native-camera, focus adjustment occurs in two scenarios (where you can place breakpoints using xcode):

  1. focusWithMode method adjusts focus if the front camera supports isFocusPointOfInterestSupported and
    AVCaptureFocusModeContinuousAutoFocus
    .

The focus mode will be changed to

AVCaptureFocusModeContinuousAutoFocus
only when the condition returns true:

[device isFocusPointOfInterestSupported] && [device isFocusModeSupported:focusMode]

If the condition returns false, autofocus may not be available, but the picture could still be focused on the ExposureMode based on this reference.

  1. updateAutoFocusPointOfInterest adjusts focus when the user taps on the screen at specific coordinates.

Given that there are multiple posts on stackoverflow indicating that certain iphone versions do not support all autofocus types with the front camera, it's recommended to set breakpoints on these lines of code and verify the values of isFocusModeSupported and isFocusPointOfInterestSupported.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is an Encrypted CoreData implementation dependent on the presence of shm and wal files?

I have integrated a secure CoreData framework called Encrypted Core Data as per recommendations. Upon inspection, I have observed that the shm and wal files are not present in the documents directory. I researched and found out that these are temporary f ...

MBProgressHUD is failing to appear

After testing different scenarios, I found that the implementation works correctly when written without using DispatchQueue main block: override func viewDidLoad() { super.viewDidLoad() MBProgressHUD.showAdded(to: navigationController!.view, animate ...

Create images from HTML pages with the help of Javascript

Hello there, UPDATE: I am looking to achieve this without relying on any third-party software. My application is a SAP product and installing additional software on every customer's system is not feasible. The situation is as follows:   ...

Unable to modify the state of data in Vue.js

After developing a weather app, I implemented some components with fields in the data section. However, when I changed the value of these fields in the methods section and attempted to access them in another method, I discovered that the old values were be ...

Turn off the nicescroll scroll bar that appears as a default feature

Is there a way to disable the nicescroll scroll bar that appears in red by default on my html page? It's causing issues with zooming in and breaking the layout. ...

The window.open function is returning a null value after attempting to open the specified

Is there a way to prevent users from opening more than one IFrame window for my application? I have included the following code: <html> <head> <title>Testing Window Opening Limitation</title> <meta http-equiv="Content-Type" cont ...

Tips for transferring variables as arguments in javascript

Currently, I am immersed in a test project aimed at expanding my knowledge of web development. Unexpectedly, I have encountered an issue that has left me puzzled on how to proceed. Within this project, there exists a table consisting of 11 cells. While 9 ...

The MUI Select component requires two clicks to open its menu if another Select component's menu is already open

I have been developing an application with two dropdowns (Select components) positioned next to each other, denoted as A and B. When A is open and the user intends to click on B to open it, I observed that in the default behavior of material UI, the user ...

What could be causing the Toast message to not show up in react-native-root-toast?

Incorporated react-native-root-toast into my expo project running on expo 51. Please see the code snippet below for reference: const toastColors = { 'error': { color: '#DA5C53', iconName: <WarningIcon size="5 ...

An issue arose while pre-rendering the page within Next.js

Recently, I developed an API using next JS in the pages/api directory and utilized it on a page located in the pages folder. During the localhost testing phase, the API functions smoothly without any issues. However, when deploying to Vercel, I encountere ...

The form is functioning properly on mobile devices but is currently experiencing issues on the server

Everything runs smoothly when accessing the website and using the form on localhost. However, once it's uploaded to a server, the form only functions correctly on desktop devices. On mobile, the form fails to filter and displays all professionals inst ...

What encodings does FileReader support?

Are you looking to easily read user-input files as text? If you can count on modern browser usage, then using FileReader is the way to go (and it works exceptionally well). reader.readAsText(myfile, encoding); It's worth noting that encoding defaul ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

Retrieve the Array Object's Name in a JSON File

I am looking for city names like Salem and Madurai from the given JSON data { "status": "success", "DisplayList": [ { "AVINASHI": [ "gmail@com", "<a href="/cdn-cgi/l/email-protection" class= ...

Generating, establishing aesthetics for a specific span

My goal is to automatically detect addresses within a page and apply the class "address" where they are found. var addressPatternApplier = function(element, pattern, style) { var innerText = element.innerText; var matches = innerText.match(pattern); ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...

How can I empty the value of a UI widget (such as an input field, select menu, or date picker) in Webix UI?

Is there a way in Webix UI to clear widget values individually, rather than collectively based on form id? I'm looking for a method using a mixin like $$(<form-id>).clear(). I need control of individual elements, so is there a proper way to res ...

Trouble encountered when attempting to push ABNewPersonViewController

While using the AddressBookUI Framework to add contacts, I encountered an issue with the cancel and done buttons not functioning properly when pushing the view controller. I would prefer not to present it. Below is the code snippet: ABNewPersonViewContro ...

Incorporating jQuery tooltips within a dynamically refreshing jQuery div

Having trouble with jQuery tooltips (using Tipsy) on a dynamically included page. The tooltips work well on regular pages, but when I include the page through PHP and set up auto-refresh using jQuery, the tooltips stop working properly. The issue seems to ...

Implementing the Disabled Attribute on a Dynamically Generated Button Using React

My QWERTY keyboard is dynamically rendered through a component as Bootstrap buttons using bootstrap-react. Each button does not have an ID to avoid relying on IDs in React. When a letter button is clicked, it triggers an onClick event passed as props back ...