我想創建相機作爲我的背景在Xamarin形式,我打算在我的共享代碼中的cameraview頂部添加的東西。如何使用手機相機作爲背景?
現在我正在做iOS設備。我現在碰到這行代碼:Frame = liveCameraStream.Bounds
帶有錯誤:對象引用未設置爲對象的實例。
所以我的問題是我怎樣才能調整我的當前代碼來獲取相機作爲背景在Xamarin形式?
這是我在iOS的渲染:
[assembly: ExportRenderer(typeof(ICameraBackground), typeof(CameraBackground_iOS))]
namespace project.iOS
{
public class CameraBackground_iOS : ViewRenderer
{
AVCaptureSession captureSession;
AVCaptureDeviceInput captureDeviceInput;
AVCaptureStillImageOutput stillImageOutput;
UIView liveCameraStream;
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
SetupLiveCameraStream();
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
SetupLiveCameraStream();
}
public async void SetupLiveCameraStream()
{
await AuthorizeCameraUse();
captureSession = new AVCaptureSession();
var videoPreviewLayer = new AVCaptureVideoPreviewLayer(captureSession)
{
Frame = liveCameraStream.Bounds
};
liveCameraStream.Layer.AddSublayer(videoPreviewLayer);
var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
ConfigureCameraForDevice(captureDevice);
captureDeviceInput = AVCaptureDeviceInput.FromDevice(captureDevice);
var dictionary = new NSMutableDictionary();
dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
stillImageOutput = new AVCaptureStillImageOutput()
{
OutputSettings = new NSDictionary()
};
captureSession.AddOutput(stillImageOutput);
captureSession.AddInput(captureDeviceInput);
captureSession.StartRunning();
}
public void ConfigureCameraForDevice(AVCaptureDevice device)
{
var error = new NSError();
if (device.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
{
device.LockForConfiguration(out error);
device.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
device.UnlockForConfiguration();
}
else if (device.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
{
device.LockForConfiguration(out error);
device.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
device.UnlockForConfiguration();
}
else if (device.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
{
device.LockForConfiguration(out error);
device.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
device.UnlockForConfiguration();
}
}
public async Task AuthorizeCameraUse()
{
var authorizationStatus = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);
if (authorizationStatus != AVAuthorizationStatus.Authorized)
{
await AVCaptureDevice.RequestAccessForMediaTypeAsync(AVMediaType.Video);
}
}
那麼,你的問題是否不如何解決死機,或如何使用相機你在應用程序中的背景?由於這個問題目前正在撰寫,所以很難說清楚。 – Demitrian
如何使用相機作爲背景。我提到我現在只是爲了展示我目前的狀況而崩潰。我會稍微更新一下該線程,以使其更加清晰!感謝您的支持 – Martman