kandi background
Explore Kits

cameraview | Easily integrate Camera features into your Android app | Camera library

 by   google Java Version: Current License: Apache-2.0

 by   google Java Version: Current License: Apache-2.0

Download this library from

kandi X-RAY | cameraview Summary

cameraview is a Java library typically used in Telecommunications, Media, Media, Entertainment, Video, Camera applications. cameraview has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. You can download it from GitHub.
This is not an official Google product. CameraView aims to help Android developers easily integrate Camera features. Requires API Level 9. The library uses Camera 1 API on API Level 9-20 and Camera2 on 21 and above.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • cameraview has a medium active ecosystem.
  • It has 4732 star(s) with 1049 fork(s). There are 157 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 149 open issues and 55 have been closed. On average issues are closed in 192 days. There are 32 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of cameraview is current.
cameraview Support
Best in #Camera
Average in #Camera
cameraview Support
Best in #Camera
Average in #Camera

quality kandi Quality

  • cameraview has 0 bugs and 0 code smells.
cameraview Quality
Best in #Camera
Average in #Camera
cameraview Quality
Best in #Camera
Average in #Camera

securitySecurity

  • cameraview has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • cameraview code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
cameraview Security
Best in #Camera
Average in #Camera
cameraview Security
Best in #Camera
Average in #Camera

license License

  • cameraview is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
cameraview License
Best in #Camera
Average in #Camera
cameraview License
Best in #Camera
Average in #Camera

buildReuse

  • cameraview releases are not available. You will need to build from source code and install.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • cameraview saves you 1382 person hours of effort in developing the same functionality from scratch.
  • It has 3094 lines of code, 262 functions and 47 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
cameraview Reuse
Best in #Camera
Average in #Camera
cameraview Reuse
Best in #Camera
Average in #Camera
Top functions reviewed by kandi - BETA

kandi has reviewed cameraview and discovered the below as its top functions. This is intended to give you an instant insight into cameraview implemented functionality, and help decide if they suit your requirements.

  • Perform a measure .
  • Capture any still photo .
  • Configures the transform for the view .
  • Handle options select item .
  • Choose the best size for the specified sizes .
  • Factory method to create a dialog dialog .
  • Creates an aspect ratio .
  • Adds a new size to the set if it does not match the provided size .
  • Enables orientation changes .
  • Set the width and height

cameraview Key Features

Camera preview by placing it in a layout XML (and calling the start method)

Configuration by attributes Aspect ratio (app:aspectRatio) Auto-focus (app:autoFocus) Flash (app:flash)

Usage

copy iconCopydownload iconDownload
<com.google.android.cameraview.CameraView
    android:id="@+id/camera"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:keepScreenOn="true"
    android:adjustViewBounds="true"
    app:autoFocus="true"
    app:aspectRatio="4:3"
    app:facing="back"
    app:flash="auto"/>

How to handle a device rotation for AVCaptureVideoPreviewLayer?

copy iconCopydownload iconDownload
struct CameraPreview: UIViewRepresentable {
    @ObservedObject var camera: CameraModel
    
    class LayerView: UIView {
        override func layoutSubviews() {
            super.layoutSubviews()
            // To disable default animation of layer. You can comment out those lines with `CATransaction` if you want to include
            CATransaction.begin() 
            CATransaction.setDisableActions(true)
            layer.sublayers?.forEach({ layer in
                layer.frame = frame
            })
            CATransaction.commit()
        }
    }
    
    func makeUIView(context: Context) -> some UIView {
        let view = LayerView()
        camera.preview = AVCaptureVideoPreviewLayer(session: camera.session)
        camera.preview.frame = view.frame
        camera.preview.videoGravity = AVLayerVideoGravity.resizeAspectFill
        view.layer.addSublayer(camera.preview)
        camera.session.startRunning()
        return view
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) {
    }
}
-----------------------
struct CameraView: View {
    @StateObject var model = CameraModel()
    var body: some View {
        CameraPreview(camera: model)
            .safeAreaInset(edge: .bottom, alignment: .center, spacing: 0) {
                Color.clear
                    .frame(height: 0)
                    .background(Material.bar)
            }
            .ignoresSafeArea(.all, edges: [.top, .horizontal])
            .onAppear() {
                model.check()
            }
    }
}

struct CameraPreview: UIViewRepresentable {
    @ObservedObject var camera: CameraModel
    
    class LayerView: UIView {
        var parent: CameraPreview! = nil
        
        override func layoutSubviews() {
            super.layoutSubviews()
            // To disable default animation of layer. You can comment out those lines with `CATransaction` if you want to include
            CATransaction.begin()
            CATransaction.setDisableActions(true)
            layer.sublayers?.forEach({ layer in
                layer.frame = UIScreen.main.bounds
            })
            self.parent.camera.rotate(orientation: UIDevice.current.orientation)
            CATransaction.commit()
        }
    }
    
    func makeUIView(context: Context) -> some UIView {
        let view = LayerView()
        view.parent = self
        camera.preview = AVCaptureVideoPreviewLayer(session: camera.session)
        camera.preview.videoGravity = AVLayerVideoGravity.resizeAspectFill
        camera.preview.frame = view.frame
        view.layer.addSublayer(camera.preview)
        camera.start()
        return view
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) {
    }
}

struct CameraView_Previews: PreviewProvider {
    static var previews: some View {
        CameraView()
    }
}

class CameraModel: ObservableObject {
    @Published var session = AVCaptureSession()
    @Published var alert = false
    @Published var preview: AVCaptureVideoPreviewLayer!
    
    func check() {
        switch AVCaptureDevice.authorizationStatus(for: .video) {
        case .authorized:
            setUp()
            break
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { (status) in
                if status {
                    self.setUp()
                }
            }
            break
        case .denied:
            self.alert.toggle()
            break
        default:
            break
        }
    }
    
    func setUp() {
        do {
            self.session.beginConfiguration()
            let device = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back)
            let input = try AVCaptureDeviceInput(device: device!)
            
            if self.session.canAddInput(input) {
                self.session.addInput(input)
            }
            
            self.session.commitConfiguration()
        }
        catch {
            print(error.localizedDescription)
        }
    }
    
    func start() {
        self.session.startRunning()
    }
    
    func rotate(orientation: UIDeviceOrientation) {
        let videoConnection = self.preview.connection
        switch orientation {
        case .portraitUpsideDown:
            videoConnection?.videoOrientation = .portraitUpsideDown
        case .landscapeLeft:
            videoConnection?.videoOrientation = .landscapeRight
        case .landscapeRight:
            videoConnection?.videoOrientation = .landscapeLeft
        case .faceDown:
            videoConnection?.videoOrientation = .portraitUpsideDown
        default:
            videoConnection?.videoOrientation = .portrait
        }
    }
}

Swiftui nested navigation issue while using navigation link

copy iconCopydownload iconDownload
struct ChildView: View {
    
    @Environment(\.presentationMode) var presentationMode

    @Binding var show: Bool
    
    var body: some View {
        Button("Assume capture success"){
            show = false
            presentationMode.wrappedValue.dismiss()
        }
    }
}

Error: Required named parameter 'path' must be provided

copy iconCopydownload iconDownload
CameraViewPage({Key? key, required this.path}) : super(key: key);
Navigator.push(context, MaterialPageRoute(builder: (builder)=> CameraViewPage(path: path)));
await _cameraController.takePicture(path: path);
-----------------------
CameraViewPage({Key? key, required this.path}) : super(key: key);
Navigator.push(context, MaterialPageRoute(builder: (builder)=> CameraViewPage(path: path)));
await _cameraController.takePicture(path: path);
-----------------------
CameraViewPage({Key? key, required this.path}) : super(key: key);
Navigator.push(context, MaterialPageRoute(builder: (builder)=> CameraViewPage(path: path)));
await _cameraController.takePicture(path: path);
-----------------------
  void takePhoto(BuildContext context) async {
       final path = join((await getTemporaryDirectory()).path,"${DateTime.now()}.png");
       await _cameraController.takePicture(path);
       Navigator.push(context, MaterialPageRoute(builder: (builder)=> CameraViewPage(path:path)));
      }

Swift UITapGestureRecognizer not calling

copy iconCopydownload iconDownload
let focusGesture = UITapGestureRecognizer(target: context.coordinator, action: #selector(context.coordinator.tapFocus(_:)))

Swiftui IGStoryKit Vertical Image flips Horizontal when sharing to Instagram Story from my app

copy iconCopydownload iconDownload
var fixOrientation: UIImage? {
        guard self.imageOrientation != .up else { return self }
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        let rect = CGRect(x: 0,
                          y: 0,
                          width: self.size.width,
                          height: self.size.height)
        self.draw(in: rect)
        guard let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
        UIGraphicsEndImageContext()
        return normalizedImage
}
let image = UIImage(data: self.picData)!
guard let fixedOrientationImage = image.fixOrientation else { return }

// Now pass this `fixedOrientationImage` to IGDispatcher
-----------------------
var fixOrientation: UIImage? {
        guard self.imageOrientation != .up else { return self }
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        let rect = CGRect(x: 0,
                          y: 0,
                          width: self.size.width,
                          height: self.size.height)
        self.draw(in: rect)
        guard let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
        UIGraphicsEndImageContext()
        return normalizedImage
}
let image = UIImage(data: self.picData)!
guard let fixedOrientationImage = image.fixOrientation else { return }

// Now pass this `fixedOrientationImage` to IGDispatcher

@Published UIImage property not updating in SwiftUI

copy iconCopydownload iconDownload
@ObservedObject var cameraViewModel 
@StateObject var cameraViewModel
-----------------------
@ObservedObject var cameraViewModel 
@StateObject var cameraViewModel

javascript- getUserMedia on Safari

copy iconCopydownload iconDownload
 navigator.mediaDevices
    .getUserMedia(constraints)
    .then(function (stream) {
        cameraView.srcObject = stream
        cameraView.onloadedmetadata = function(e) {
            cameraView.play()
        }
      })
    .catch(function (error) {
        alert(error)
    })
-----------------------
            <video id="camera--view" muted autoplay playsinline></video>

metadataOutputRectConverted(fromLayerRect:) in Android

copy iconCopydownload iconDownload
private fun cropImage(bitmap: Bitmap, cameraFrame: View, cropRectFrame: View): Bitmap {
    val scaleFactor: Double; val widthOffset: Double; val heightOffset: Double

    if (cameraFrame.height * bitmap.width > cameraFrame.height * bitmap.width) {
        scaleFactor = (bitmap.width).toDouble() / (cameraFrame.width).toDouble()
        widthOffset = 0.0
        heightOffset = (bitmap.height - cameraFrame.height * scaleFactor) / 2
    } else {
        scaleFactor = (bitmap.height).toDouble() / (cameraFrame.height).toDouble()
        widthOffset = (bitmap.width - cameraFrame.width * scaleFactor) / 2
        heightOffset = 0.0
    }

    val newX = cropRectFrame.left * scaleFactor + widthOffset
    val newY = cropRectFrame.top * scaleFactor + heightOffset
    val width = cropRectFrame.width * scaleFactor
    val height = cropRectFrame.height * scaleFactor

    return Bitmap.createBitmap(bitmap, (newX).toInt(), (newY).toInt(), (width).toInt(), (height).toInt())

}

SwiftUI- server not receiving base64 string

copy iconCopydownload iconDownload
func takePic(){
    DispatchQueue.global(qos: .background).async {
        self.output.capturePhoto(with: AVCapturePhotoSettings(), delegate: self)
        DispatchQueue.main.async {
            Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { (timer) in
                self.session.stopRunning()
            }
        }
        
        DispatchQueue.main.async {
            withAnimation{self.isTaken.toggle()}
        }
        print("pic taken...")
    }
}
-----------------------
func takePic(){
    DispatchQueue.global(qos: .background).async {
        self.output.capturePhoto(with: AVCapturePhotoSettings(), delegate: self)
        self.session.stopRunning()
        
        //DispatchQueue.main.async {
        //    withAnimation{self.isTaken.toggle()}  // << IT ISNT TAKEN YET
        //}
        //print("pic taken...")  // << AGAIN IT ISNT TAKEN YET
    }
}
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {

    // NOW ITS TAKEN BUT MAY HAVE ERRORS

    if error != nil{
        return  // MAYBE THIS NEED SOME BETTER FEEDBACK FOR THE USER
    }
    
    guard let imageData = photo.fileDataRepresentation() else{return}  // USER FEEDBACK??

    self.picData = imageData

    // NOW ITS TAKEN


    // I'm assuming this is running on the main thread.
    withAnimation{self.isTaken.toggle()} // SO TOGGLE isTaken
}
-----------------------
func takePic(){
    DispatchQueue.global(qos: .background).async {
        self.output.capturePhoto(with: AVCapturePhotoSettings(), delegate: self)
        self.session.stopRunning()
        
        //DispatchQueue.main.async {
        //    withAnimation{self.isTaken.toggle()}  // << IT ISNT TAKEN YET
        //}
        //print("pic taken...")  // << AGAIN IT ISNT TAKEN YET
    }
}
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {

    // NOW ITS TAKEN BUT MAY HAVE ERRORS

    if error != nil{
        return  // MAYBE THIS NEED SOME BETTER FEEDBACK FOR THE USER
    }
    
    guard let imageData = photo.fileDataRepresentation() else{return}  // USER FEEDBACK??

    self.picData = imageData

    // NOW ITS TAKEN


    // I'm assuming this is running on the main thread.
    withAnimation{self.isTaken.toggle()} // SO TOGGLE isTaken
}

how can I create a rectangular as big as the screen in Xamarin Forms?

copy iconCopydownload iconDownload
<AbsoluteLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
    <xct:CameraView x:Name="cameraView"  CameraOptions="Back" CaptureMode="Photo" OnAvailable="CameraView_OnAvailable" AbsoluteLayout.LayoutBounds="0.5,0.5,1,1" AbsoluteLayout.LayoutFlags="All">
        <xct:CameraView.Behaviors >
            <xct:EventToCommandBehavior Command="{Binding PhotoCapturedCommand}" EventName="MediaCaptured" />
        </xct:CameraView.Behaviors>
    </xct:CameraView>
    <Frame BackgroundColor="Transparent" BorderColor="White" AbsoluteLayout.LayoutBounds="0.5,0.5,0.5,0.5" AbsoluteLayout.LayoutFlags="All"/>
</AbsoluteLayout>

Community Discussions

Trending Discussions on cameraview
  • How to handle a device rotation for AVCaptureVideoPreviewLayer?
  • Swiftui nested navigation issue while using navigation link
  • Error: Required named parameter 'path' must be provided
  • Swift UITapGestureRecognizer not calling
  • Swiftui IGStoryKit Vertical Image flips Horizontal when sharing to Instagram Story from my app
  • Could not resolve org.webkit:android-jsc:+
  • @Published UIImage property not updating in SwiftUI
  • javascript- getUserMedia on Safari
  • metadataOutputRectConverted(fromLayerRect:) in Android
  • SwiftUI- server not receiving base64 string
Trending Discussions on cameraview

QUESTION

How to handle a device rotation for AVCaptureVideoPreviewLayer?

Asked 2022-Apr-01 at 21:27

I have a simple camera preview implementation:

import SwiftUI
import AVFoundation

struct CameraView: View {
    @StateObject var model = CameraModel()
    var body: some View {
        CameraPreview(camera: model)
            .safeAreaInset(edge: .bottom, alignment: .center, spacing: 0) {
                Color.clear
                    .frame(height: 0)
                    .background(Material.bar)
            }
            .ignoresSafeArea(.all, edges: .top)
            .onAppear() {
                model.check()
            }
    }
}

struct CameraPreview: UIViewRepresentable {
    @ObservedObject var camera: CameraModel
    
    func makeUIView(context: Context) -> some UIView {
        let view = UIView(frame: UIScreen.main.bounds)
        camera.preview = AVCaptureVideoPreviewLayer(session: camera.session)
        camera.preview.videoGravity = AVLayerVideoGravity.resizeAspectFill
        camera.preview.frame = view.frame
        view.layer.addSublayer(camera.preview)
        camera.start()
        return view
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) {
    }
}

struct CameraView_Previews: PreviewProvider {
    static var previews: some View {
        CameraView()
    }
}

class CameraModel: ObservableObject {
    @Published var session = AVCaptureSession()
    @Published var alert = false
    @Published var preview: AVCaptureVideoPreviewLayer!
    
    func check() {
        switch AVCaptureDevice.authorizationStatus(for: .video) {
        case .authorized:
            setUp()
            break
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { (status) in
                if status {
                    self.setUp()
                }
            }
            break
        case .denied:
            self.alert.toggle()
            break
        default:
            break
        }
    }
    
    func setUp() {
        do {
            self.session.beginConfiguration()
            let device = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back)
            let input = try AVCaptureDeviceInput(device: device!)
            
            if self.session.canAddInput(input) {
                self.session.addInput(input)
            }
            
            self.session.commitConfiguration()
        }
        catch {
            print(error.localizedDescription)
        }
    }
    
    func start() {
        self.session.startRunning()
    }
}

The problem is that it doesn't handle screen rotations:

Screenshot

I found similar topics, for example, this one, but I am a noobie in iOS development, I can't even understand where to put this solution. I've checked neither View, nor UIViewRepresentable have such methods to override.

How to handle screen rotation in AVCaptureVideoPreviewLayer?

ANSWER

Answered 2022-Apr-01 at 06:29

If you want to update layer frame in rotation, you need to create custom UIView and override layoutSubviews(). Inside layoutSubviews(), you need to update frame for sublayers.

The code will be as below.

struct CameraPreview: UIViewRepresentable {
    @ObservedObject var camera: CameraModel
    
    class LayerView: UIView {
        override func layoutSubviews() {
            super.layoutSubviews()
            // To disable default animation of layer. You can comment out those lines with `CATransaction` if you want to include
            CATransaction.begin() 
            CATransaction.setDisableActions(true)
            layer.sublayers?.forEach({ layer in
                layer.frame = frame
            })
            CATransaction.commit()
        }
    }
    
    func makeUIView(context: Context) -> some UIView {
        let view = LayerView()
        camera.preview = AVCaptureVideoPreviewLayer(session: camera.session)
        camera.preview.frame = view.frame
        camera.preview.videoGravity = AVLayerVideoGravity.resizeAspectFill
        view.layer.addSublayer(camera.preview)
        camera.session.startRunning()
        return view
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) {
    }
}

Source https://stackoverflow.com/questions/71700250

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install cameraview

You can download it from GitHub.
You can use cameraview like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the cameraview component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.