UIView ignoring size constraints when AVCaptureVideoPreviewLayer subview added
Hello and Happy Monday!
I am trying to build a custom camera, similar in appearance to Instagram's.
To begin, I used Storyboard to add a UIView, centered the UIView vertically & horizontally, and set the width and height to 200 via storyboard.
Then, in my code, I added the AVCaptureVideoPreviewLayer to my UIView, which I called cameraView
, and then set the frame for the AVCaptureVideoPreviewLayer to my UIView frame.
ISSUE: It seems as if the UIView's Width and Height constraints get ignored. The camera preview should be within the very center of the view, but it is not. What am I doing wrong here? I suppose it has something to do with the preview layer. Or maybe I need to be using a UIImageView instead of a UIView?
Any input would be much appreciated! Thanks!
Here is a screenshot of exactly what it looks like... Note: Highlight the image to see where the edges of the screenshot are, sorry about that.
My Code:
extension String {
func stripCharactersInSet(chars: [Character]) -> String {
return String(filter(self) {find(chars, $0) == nil})
}
}
class MyCameraViewController: UIViewController {
let session = AVCaptureSession()
var captureDevice: AVCaptureDevice?
var previewLayer: AVCaptureVideoPreviewLayer?
var stillImageOutput = AVCaptureStillImageOutput()
var imageData: NSData!
@IBOutlet weak var capturePhotoButton: UIButton!
@IBOutlet weak var flashButton: UIButton!
@IBOutlet weak var cameraView: UIView!
override func prefersStatusBarHidden() -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
//flashButton.hidden = true
if(session.canSetSessionPreset(AVCaptureSessionPresetHigh)) {
session.sessionPreset = AVCaptureSessionPresetHigh
} else {
println("Cannot Set session Preset to AVCaptureSessionPresetPhoto")
}
let devices = AVCaptureDevice.devices()
for device in devices {
if(device.hasMediaType(AVMediaTypeVideo)){
if(device.position == AVCaptureDevicePosition.Front){
captureDevice = device as? AVCaptureDevice
if captureDevice != nil {
beginSession()
}
}
}
}
}
func setCaptureDevice() {
let devices = AVCaptureDevice.devices()
for device in devices {
if(device.hasMediaType(AVMediaTypeVideo)){
if(device.position == AVCaptureDevicePosition.Back){
captureDevice = device as? AVCaptureDevice
}
}
}
}
@IBAction func flashButtonPressed(sender: UIButton) {
if captureDevice!.hasFlash {
if captureDevice!.isFlashModeSupported(AVCaptureFlashMode.On) {
if (captureDevice!.lockForConfiguration(nil)) {
if (captureDevice!.flashActive) {
captureDevice!.flashMode = AVCaptureFlashMode.Off
flashButton.setTitle("Flash Off", forState: UIControlState.Normal)
} else {
captureDevice!.flashMode = AVCaptureFlashMode.On
flashButton.setTitle("Flash On", forState: UIControlState.Normal)
}
}
captureDevice!.unlockForConfiguration()
}
}
}
@IBAction func switchCamera(sender: UIButton) {
let currentCameraInput: AVCaptureInput = session.inputs[0] as! AVCaptureInput
session.removeInput(currentCameraInput)
let newCamera: AVCaptureDevice?
if(captureDevice!.position == AVCaptureDevicePosition.Back){
println("Setting new camera with Front")
flashButton.hidden = true
newCamera = self.cameraWithPosition(AVCaptureDevicePosition.Front)
} else {
println("Setting new camera with Back")
flashButton.hidden = false
newCamera = self.cameraWithPosition(AVCaptureDevicePosition.Back)
}
let newVideoInput = AVCaptureDeviceInput(device: newCamera!, error: nil)
if(newVideoInput != nil) {
session.addInput(newVideoInput)
} else {
println("Error creating capture device input")
}
captureDevice! = newCamera!
session.commitConfiguration()
}
func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice {
let devices = AVCaptureDevice.devices()
for device in devices {
if(device.position == position){
return device as! AVCaptureDevice
}
}
return AVCaptureDevice()
}
func beginSession() {
if(captureDevice!.isFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus)) {
captureDevice?.focusMode = AVCaptureFocusMode.ContinuousAutoFocus
}
var err : NSError? = nil
//Add Input, which is my captureDevice
session.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
if err != nil {
println("error: (err?.localizedDescription)")
}
previewLayer = AVCaptureVideoPreviewLayer(session: session)
//self.view.layer.addSublayer(previewLayer)
cameraView.layer.addSublayer(previewLayer)
//previewLayer?.frame = self.view.layer.frame
previewLayer?.frame = cameraView.layer.frame
session.startRunning()
}
struct imageViewStruct {
static var image: UIImage?
}
@IBAction func shotPress(sender: UIButton) {
stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
if session.canAddOutput(stillImageOutput) {
session.addOutput(stillImageOutput)
}
var videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
if videoConnection != nil {
stillImageOutput.captureStillImageAsynchronouslyFromConnection(stillImageOutput.connectionWithMediaType(AVMediaTypeVideo))
{ (imageDataSampleBuffer, error) -> Void in
self.imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
var dataProvider = CGDataProviderCreateWithCFData(self.imageData)
var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)
var image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Up)
imageViewStruct.image = image
//self.uploadPhoto(image!)
self.presentPhotoEditViewController(image!)
}}
}
func setupPhotoEditor() {
//Remove existing camera stuff
previewLayer?.removeFromSuperlayer()
}
func presentPhotoEditViewController(imageToSend: UIImage) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("photoEditor") as! PhotoEditViewController
self.presentViewController(vc, animated: true, completion: nil)
}
func uploadPhoto(image: UIImage) {
let imageData = UIImagePNGRepresentation(image)
let imageFile = PFFile(name:"image.png", data:imageData)
var userPhoto = PFObject(className:getStringForVenue())
userPhoto["imageFile"] = imageFile
userPhoto.saveInBackground()
}
func getStringForVenue() -> String {
let initialVenueString = LocViewController.variables.selectedVenue
let chars: [Character] = ["'",",",":"," "]
println(initialVenueString.stripCharactersInSet(chars))
return initialVenueString.stripCharactersInSet(chars)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Your method bigSession() should have some settings for the AVCaptureVideoPreviewLayer: setVideoGravity and setFrame.
OBJ-C
[previewLayer setVideoGravity: AVLayerVideoGravityResizeAspectFill];
[previewLayer setFrame:self.cameraView.layer.bounds];
This will set your video aspect view to fit the view layer's frame you assigned it for.
链接地址: http://www.djcxy.com/p/74272.html