Skip to content

Commit

Permalink
feat: Add takeSnapshot() to PreviewView
Browse files Browse the repository at this point in the history
  • Loading branch information
mrousavy committed Feb 29, 2024
1 parent 532837d commit e17eb50
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions package/ios/Core/CameraError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ enum CaptureError {
case createRecorderError(message: String? = nil)
case videoNotEnabled
case photoNotEnabled
case snapshotFailed
case aborted
case insufficientStorage
case unknown(message: String? = nil)
Expand All @@ -197,6 +198,8 @@ enum CaptureError {
return "create-recorder-error"
case .videoNotEnabled:
return "video-not-enabled"
case .snapshotFailed:
return "snapshot-failed"
case .photoNotEnabled:
return "photo-not-enabled"
case .insufficientStorage:
Expand All @@ -222,6 +225,8 @@ enum CaptureError {
return "Failed to create the AVAssetWriter (Recorder)! \(message ?? "(no additional message)")"
case .videoNotEnabled:
return "Video capture is disabled! Pass `video={true}` to enable video recordings."
case .snapshotFailed:
return "Failed to take a Snapshot of the Preview View! Try using takePhoto() instead."
case .photoNotEnabled:
return "Photo capture is disabled! Pass `photo={true}` to enable photo capture."
case .aborted:
Expand Down
17 changes: 17 additions & 0 deletions package/ios/Core/PreviewView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,23 @@ class PreviewView: UIView {
return videoPreviewLayer.captureDevicePointConverted(fromLayerPoint: point)
}

func takeSnapshot() throws -> UIImage {
UIGraphicsBeginImageContextWithOptions(videoPreviewLayer.frame.size, false, 0)
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else {
throw CameraError.capture(.snapshotFailed)
}

videoPreviewLayer.render(in: context)

guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
throw CameraError.capture(.snapshotFailed)
}
return image
}

init(frame: CGRect, session: AVCaptureSession) {
super.init(frame: frame)
videoPreviewLayer.session = session
Expand Down

0 comments on commit e17eb50

Please sign in to comment.