AVCaptureVideoPreviewLayer并从相机位置预览 [英] AVCaptureVideoPreviewLayer and preview from camera position
问题描述
我正在开发一款允许用户拍照的应用。
我开始使用 AVCam 苹果提供,但我实际上有一个问题
我无法将相机层定位在我想要的位置,但它会自动定位在视图的中心
I'm developing an app that permits user to takes photo. I've started using AVCam apple provides but i'm actually have a problem Simply i cannot position the camera layer where i want but it's positioned automatically on center of the View
在左侧,您可以看到我实际上有什么,在右边我想拥有什么。
包含来自相机的预览的视图是 UIView
子类,这是代码
On the left side you can see what i actually have, on the right side what i'd like to have.
The View that contains the preview that comes from the camera is a UIView
subclass and this is the code
class AVPreviewView : UIView {
override class func layerClass() -> AnyClass {
return AVCaptureVideoPreviewLayer.self
}
func session () -> AVCaptureSession {
return (self.layer as AVCaptureVideoPreviewLayer).session
}
func setSession(session : AVCaptureSession) -> Void {
(self.layer as AVCaptureVideoPreviewLayer).session = session;
(self.layer as AVCaptureVideoPreviewLayer).videoGravity = AVLayerVideoGravityResizeAspect;
}
}
感谢任何帮助
推荐答案
首先获取屏幕尺寸,以便计算宽高比
First get your screen size so you can calculate the aspect ratio
let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
var aspectRatio: CGFloat = 1.0
var viewFinderHeight: CGFloat = 0.0
var viewFinderWidth: CGFloat = 0.0
var viewFinderMarginLeft: CGFloat = 0.0
var viewFinderMarginTop: CGFlaot = 0.0
现在计算预览图层的大小。
Now calculate the size of the preview layer.
func setSession(session : AVCaptureSession) -> Void {
if screenWidth > screenHeight {
aspectRatio = screenHeight / screenWidth * aspectRatio
viewFinderWidth = self.bounds.width
viewFinderHeight = self.bounds.height * aspectRatio
viewFinderMarginTop *= aspectRatio
} else {
aspectRatio = screenWidth / screenHeight
viewFinderWidth = self.bounds.width * aspectRatio
viewFinderHeight = self.bounds.height
viewFinderMarginLeft *= aspectRatio
}
(self.layer as AVCaptureVideoPreviewLayer).session = session;
将图层的 videoGravity
设置为 AVLayerVideoGravityResizeAspectFill
以便图层延伸到给定的自定义视图。
Set the layer's videoGravity
to AVLayerVideoGravityResizeAspectFill
so that the layer stretches to fill given your custom view.
(self.layer as AVCaptureVideoPreviewLayer).videoGravity = AVLayerVideoGravityResizeAspectFill;
最后,将预览图层的框架设置为上面计算的值,使用您喜欢的任何偏移量。
Finally, set the frame of your preview layer to the values calculated above with any offset that you like.
(self.layer as AVCaptureVideoPreviewLayer).frame = CGRectMake(viewFinderMarginLeft, viewFinderMarginTop, viewFinderWidth, viewFinderHeight)
}
这可能需要一些调整,因为我没有现场测试,但你应该是能够创建一个更灵活的VideoPreviewArea,它由APPreviewView的边界分隔。
This may take some tweaking since I haven't tested it live, but you should be able to create a more flexible VideoPreviewArea delimited by the bounds of your APPreviewView.
这篇关于AVCaptureVideoPreviewLayer并从相机位置预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!