1. 程式人生 > >xamarin.form 新增拍照功能

xamarin.form 新增拍照功能

  1。使用nuget安裝安裝XLabs.Serialization.JSON,和XLabs.Forms

  2。在android端增加如下程式碼

  

[Activity(Label = "App2", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : XFormsApplicationDroid
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            //TabLayoutResource = Resource.Layout.Tabbar;
            //ToolbarResource = Resource.Layout.Toolbar;
            
            SetIoc();
            base.OnCreate(savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
        private void SetIoc()
        {
            var resolverContainer = new global::XLabs.Ioc.SimpleContainer();
            resolverContainer.Register<IMediaPicker, MediaPicker>();
            XLabs.Ioc.Resolver.SetResolver(resolverContainer.GetResolver());
        }

  在IOS端增加如下程式碼

// The UIApplicationDelegate for the application. This class is responsible for launching the 
    // User Interface of the application, as well as listening (and optionally responding) to 
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : XLabs.Forms.XFormsApplicationDelegate
    {
        //
        // This method is invoked when the application has loaded and is ready to run. In this 
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            
            SetIoc();
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
        private void SetIoc()
        {
            var resolverContainer = new global::XLabs.Ioc.SimpleContainer();
            resolverContainer.Register<IMediaPicker, MediaPicker>();
            XLabs.Ioc.Resolver.SetResolver(resolverContainer.GetResolver());
        }
    }

  在ios端,需要編輯info.plist,增加相機使用許可權

<key>NSCameraUsageDescription</key>
	<string>App需要您的同意,才能訪問相機</string>

  在android端需要右鍵-》屬性-》Android清單-》所需許可權中勾選CAMER和WRITE_EXTERNAL_STORAGE

  如果你需要選取照片功能

private async void Button_Clicked_1(object sender, EventArgs e)
        {
            IMediaPicker mediaPicker = Resolver.Resolve<IMediaPicker>();
            var mediaFile = await mediaPicker.SelectPhotoAsync(new CameraMediaStorageOptions
            {
                DefaultCamera = CameraDevice.Front,
            });
            Photo.Source = ImageSource.FromFile(mediaFile.Path);
        }