-
-
Save dbeattie71/9631328 to your computer and use it in GitHub Desktop.
Simple example of capturing a still image with AVCaptureDevice.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void initCameraView(){ | |
NSError error = null; | |
captureSession = new AVCaptureSession(){ | |
SessionPreset=AVCaptureSession.Preset640x480 | |
}; | |
var device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video); | |
var deviceInput = AVCaptureDeviceInput.FromDevice(device,out error); | |
if(error!=null){ | |
displayErrorOnMainQueueWithMessage(error,"Unable to setup capture"); | |
return; | |
} | |
if(captureSession.CanAddInput(deviceInput)){ | |
captureSession.AddInput(deviceInput); | |
} | |
//create still image output | |
stillImageOutput = new AVCaptureStillImageOutput(); | |
if(captureSession.CanAddOutput(stillImageOutput)){ | |
captureSession.AddOutput(stillImageOutput); | |
} | |
previewLayer = new AVCaptureVideoPreviewLayer(captureSession){ | |
BackgroundColor = UIColor.Black.CGColor, | |
VideoGravity = AVPlayerLayer.GravityResizeAspect | |
}; | |
var rootLayer = this.PreviewView.Layer; | |
rootLayer.MasksToBounds = true; | |
previewLayer.Frame = rootLayer.Bounds; | |
rootLayer.AddSublayer(previewLayer); | |
captureSession.StartRunning(); | |
} | |
void TakePhoto(object sender,EventArgs eventArgs){ | |
var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video); | |
if(videoConnection==null){ | |
return; | |
} | |
stillImageOutput.CaptureStillImageAsynchronously(videoConnection,(imageDataSampleBuffer,error)=>{ | |
if(error!=null){ | |
this.displayErrorOnMainQueueWithMessage(error,"Unable to take photo"); | |
return; | |
} | |
var jpgData = AVCaptureStillImageOutput.JpegStillToNSData(imageDataSampleBuffer); | |
var uiImage = UIImage.LoadFromData(jpgData); | |
ALAssetsLibrary library = new ALAssetsLibrary(); | |
library.WriteImageToSavedPhotosAlbum(uiImage,(ALAssetOrientation)uiImage.Orientation,(assetUrl,saveerror)=>{ | |
//!!saveerror is set to NSError with "Failed to encode image for saved photos." and error code -3304 | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment