在Xamarin.Forms中访问相机

本文关键字:访问 相机 Forms Xamarin | 更新日期: 2023-09-27 18:02:13

我需要使用Xamarin Forms PCL访问相机。我找不到任何有效的样本。

我尝试安装XLab并使用其示例代码,但它有异常。例如,对于XLabs示例,我使用以下命令:

/// <summary>
/// Takes the picture.
/// </summary>
/// <returns>Take Picture Task.</returns>
internal async Task<MediaFile> TakePicture()
{
    Setup();
    ImageSource = null;
    return await _mediaPicker.TakePhotoAsync(new CameraMediaStorageOptions { DefaultCamera = CameraDevice.Front, MaxPixelDimension = 400 }).ContinueWith(t =>
    {
        if (t.IsFaulted)
        {
            Status = t.Exception.InnerException.ToString();
        }
        else if (t.IsCanceled)
        {
            Status = "Canceled";
        }
        else
        {
            var mediaFile = t.Result;
            ImageSource = ImageSource.FromStream(() => mediaFile.Source);
            return mediaFile;
        }
        return null;
    }, _scheduler);
}
/// <summary>
/// Setups this instance.
/// </summary>
private void Setup()
{
    if (_mediaPicker != null)
    {
        return;
    }
    var device = Resolver.Resolve<IDevice>();
    ////RM: hack for working on windows phone? 
    _mediaPicker = DependencyService.Get<IMediaPicker>() ?? device.MediaPicker;
}

我在Resolver.Resolve<IDevice>():上得到以下异常IResolver has not been set. Please set it by calling Resolver.SetResolver(resolver)

我如何使用这个或其他替代品与Xamarin.Forms拍照?感谢任何提示提前!

在Xamarin.Forms中访问相机

添加您的Droid项目,类MainActivity以下代码

protected override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);
    #region Resolver Init
    SimpleContainer container = new SimpleContainer();
    container.Register<IDevice>(t => AndroidDevice.CurrentDevice);
    container.Register<IDisplay>(t => t.Resolve<IDevice>().Display);
    container.Register<INetwork>(t => t.Resolve<IDevice>().Network);
    Resolver.SetResolver(container.GetResolver());
    #endregion
    ....
}

和在IOS类AppDelegate中这个:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    #region Resolver Init
    SimpleContainer container = new SimpleContainer();
    container.Register<IDevice>(t => AppleDevice.CurrentDevice);
    container.Register<IDisplay>(t => t.Resolve<IDevice>().Display);
    container.Register<INetwork>(t => t.Resolve<IDevice>().Network);
    Resolver.SetResolver(container.GetResolver());
    #endregion
    ....
}

下面是xLabs Camera的示例代码:
https://www.dropbox.com/s/9paojg1q43ahnqk/XPA_PickMedia_XLabs_XFP.zip?dl=0从这里的论坛找到的:https://forums.xamarin.com/discussion/35636/a-sample-project-using-camera-control-mediapicker-of-xlabs

您不能直接访问Xamarin.Forms中的本机功能。你必须使用依赖服务来访问本地功能,如访问相机,音频等。

试试:http://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/

您必须配置IoC以使其工作,并使用Resolver将IoC提供程序设置为Resolver。SetResolver方法。在这里阅读更多内容,https://github.com/XLabs/Xamarin-Forms-Labs/wiki/IOC