1
resposta

Camera IOS

Como devo proceder para acionar a camera do IPhone? É da mesma forma que do Android?

1 resposta

Olá, João Paulo!

Infelizmente no nosso curso não apresentamos o código para realizar essa tarefa com iOS. Porém, como é um assunto recorrente no fórum da própria Xamarin, você pode baixar o código criado por um usuário daquele fórum (Vaka Gopi Nadh Reddy) e comparar a implementação da captura da imagem da câmera do iOS com a do Android.

O link para o fórum é:

https://forums.xamarin.com/discussion/42600/how-to-take-picture-from-camera-and-retrieve-it-using-xamarin-forms-for-cross-platform-app

Baixe o código do aplicativo "Gallery And Camera Sample" no link abaixo:

https://us.v-cdn.net/5019960/uploads/editor/nu/299jnzqx1yry.zip

Basicamente, o que ele faz é criar uma interface ICameraGallery e implementar duas versões dessa interface, uma chamada Android_dependency e outra Ios_Dependency, que são obtidas pela aplicação Xamarin através do Dependency Service do Xamarin Forms.

Código do ICameraGallery:

    public interface ICameraGallery
    {
        void CameraMedia();
        void GalleryMedia();
    }

Código da Android_dependency

using System;
using Android.App;
using Android.Content;
using Android.Provider;
using GalleryAndCameraSample.Droid;
using Xamarin.Forms;
using Environment = Android.OS.Environment;
using Uri = Android.Net.Uri;

[assembly: Dependency(typeof(Android_dependency))]
namespace GalleryAndCameraSample.Droid
{
    public class Android_dependency : Activity, ICameraGallery
    {
        public void CameraMedia()
        {

            AppClass._dir = new Java.IO.File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures), "CameraAppDemo");
            if (!AppClass._dir.Exists())
            {
                AppClass._dir.Mkdirs();
            }

            Intent intent = new Intent(MediaStore.ActionImageCapture);

            AppClass._file = new Java.IO.File(AppClass._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid()));

            intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(AppClass._file));

            Activity activity = (Activity)Forms.Context;
            activity.StartActivityForResult(intent, 0);
        }

        public void GalleryMedia()
        {
            var imageIntent = new Intent();
            imageIntent.SetType("image/*");
            imageIntent.SetAction(Intent.ActionGetContent);
            ((Activity)Forms.Context).StartActivityForResult(Intent.CreateChooser(imageIntent, "Select photo"), 1);
        }
    }

}

Código da Ios_Dependency:

using System;
using AVFoundation;
using CoreGraphics;
using Foundation;
using GalleryAndCameraSample.iOS;
using UIKit;
using Xamarin.Forms;

[assembly: Dependency(typeof(Ios_Dependency))]
namespace GalleryAndCameraSample.iOS
{
    public class Ios_Dependency : ICameraGallery
    {
        public async void CameraMedia()
        {
            var authorizationStatus = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);
            if (authorizationStatus != AVAuthorizationStatus.Authorized)
            {
                var access = await AVCaptureDevice.RequestAccessForMediaTypeAsync(AVMediaType.Video);
                if (access)
                {
                    GotAccessToCamera();
                }
            }
            else
            {
                GotAccessToCamera();
            }

        }

        public void GalleryMedia()
        {

            var imagePicker = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary) };
            imagePicker.AllowsEditing = true;

            var window = UIApplication.SharedApplication.KeyWindow;
            var vc = window.RootViewController;
            while (vc.PresentedViewController != null)
            {
                vc = vc.PresentedViewController;
            }

            vc.PresentViewController(imagePicker, true, null);

            imagePicker.FinishedPickingMedia += (sender, e) =>
            {
                UIImage originalImage = e.Info[UIImagePickerController.EditedImage] as UIImage;
                if (originalImage != null)
                {
                    var pngImage = originalImage.AsPNG();
                    byte[] myByteArray = new byte[pngImage.Length];
                    System.Runtime.InteropServices.Marshal.Copy(pngImage.Bytes, myByteArray, 0, Convert.ToInt32(pngImage.Length));

                    SamplePage.Galleryimage(myByteArray);
                }

                Device.BeginInvokeOnMainThread(() =>
                        {
                            vc.DismissViewController(true, null);
                        });
            };
            imagePicker.Canceled += (sender, e) => vc.DismissViewController(true, null);

        }

        private void GotAccessToCamera()
        {
            var imagePicker = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.Camera };

            var window = UIApplication.SharedApplication.KeyWindow;
            var vc = window.RootViewController;
            while (vc.PresentedViewController != null)
            {
                vc = vc.PresentedViewController;
            }

            vc.PresentViewController(imagePicker, true, null);

            imagePicker.FinishedPickingMedia += (sender, e) =>
            {
                UIImage image = (UIImage)e.Info.ObjectForKey(new NSString("UIImagePickerControllerOriginalImage"));

                UIImage rotateImage = RotateImage(image, image.Orientation);

                rotateImage = rotateImage.Scale(new CGSize(rotateImage.Size.Width, rotateImage.Size.Height), 0.5f);

                var jpegImage = rotateImage.AsJPEG();

                byte[] myByteArray = new byte[jpegImage.Length];
                System.Runtime.InteropServices.Marshal.Copy(jpegImage.Bytes, myByteArray, 0, Convert.ToInt32(jpegImage.Length));

                SamplePage.Cameraimage(myByteArray);

                Device.BeginInvokeOnMainThread(() =>
                {
                    vc.DismissViewController(true, null);
                });
            };


            imagePicker.Canceled += (sender, e) => vc.DismissViewController(true, null);
        }

        double radians(double degrees) { return degrees * Math.PI / 180; }

        private UIImage RotateImage(UIImage src, UIImageOrientation orientation)
        {
            UIGraphics.BeginImageContext(src.Size);

            if (orientation == UIImageOrientation.Right)
            {
                CGAffineTransform.MakeRotation((nfloat)radians(90));
            }
            else if (orientation == UIImageOrientation.Left)
            {
                CGAffineTransform.MakeRotation((nfloat)radians(-90));
            }
            else if (orientation == UIImageOrientation.Down)
            {

            }
            else if (orientation == UIImageOrientation.Up)
            {
                CGAffineTransform.MakeRotation((nfloat)radians(90));
            }

            src.Draw(new CGPoint(0, 0));
            UIImage image = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();
            return image;
        }

    }
}

Então você pode baixar o código, adaptar para o seu projeto e ver se funciona. E nos avise se encontrar alguma dificuldade.

Boa sorte e bons estudos!