捏合手势迅速放大和缩小相机

时间:2019-07-01 11:30:15

标签: swift uigesturerecognizer avcapturesession avcapturedevice

我在应用中使用前置摄像头。我希望在拍照时用户可以放大和缩小相机

我尝试了这段代码

let device = AVCaptureDevice.default(for: .video)
print(sender.scale)
let vZoomFactor = sender.scale * prevZoomFactor
if sender.state == .ended {
    prevZoomFactor = vZoomFactor >= 1 ? vZoomFactor : 1
}

if sender.state == .changed{
    do {
        try device!.lockForConfiguration()
        if (vZoomFactor <= device!.activeFormat.videoMaxZoomFactor) {
            device!.videoZoomFactor = max(1.0, min(vZoomFactor, device!.activeFormat.videoMaxZoomFactor))
            device?.unlockForConfiguration()
        } else {
            print("Unable to set videoZoom: (max \(device!.activeFormat.videoMaxZoomFactor), asked \(vZoomFactor))")
        }
    } catch {
        print("\(error.localizedDescription)")
    }
}

在后置摄像头中,一切正常,但在前置摄像头中未应用变焦。

1 个答案:

答案 0 :(得分:5)

好吧,花了几个小时在这段代码上之后,我到达了我犯错的地方。

Map<String, ColorUsages> colors = new HashMap<>();

ColorUsage.Builder usedColorUsage = ColorUsage.builder();
ColorUsage.Builder notUsedColorUsage = ColorUsage.builder();

usedColorUsage.addResultsItem(row.color());

ColorUsages.Builder colorUsagesBuilder = ColorUsages.builder();

ColorUsages colorUsages = colorUsagesBuilder
                        .used(usedColorUsage.build())
                        .notUsed(notUsedColorUsage.build())
                        .build();

colors.put(row.painter_id(), colorUsages);

默认情况下,这将使后置摄像头正常工作,但是当我将其切换为前置摄像头之前,直到将其视为后置摄像头为止,所以我只添加了一个条件

let device = AVCaptureDevice.default(for: .video)

这对我来说很好