35

有没有人能给出一个简短的、独立的例子来说明如何使用 Xamarin.Forms 1.3.x 访问相机?只需调用本机相机应用程序并检索结果图片就可以了。在 Xamarin.Forms 页面上显示实时视图会很棒!

我已经尝试使用 Xamarin.Mobile 和 Xamarin.Forms.Labs,但我无法在这两个平台上找到任何解决方案(目前专注于 Android 和 iOS)。在网上找到的大多数代码片段(包括stackoverflow)都是不完整的,例如没有显示IMediaPicker 对象的实现或在哪里锚定拍照方法。

4

4 回答 4

38

我终于为 iOS 和 Android 创建了一个最低限度的解决方案。

共享项目

首先,让我们看看共享代码。App为了在共享类和特定于平台的代码之间轻松交互,我们将静态存储Instancepublic static App

public static App Instance;

此外,我们将显示一个Image,稍后将填充内容。所以我们创建一个成员:

readonly Image image = new Image();

App构造函数中,我们存储Instance并创建页面内容,这是一个简单button的前面提到的image

public App()
{
   Instance = this;

   var button = new Button {
       Text = "Snap!",
       Command = new Command(o => ShouldTakePicture()),
   };

   MainPage = new ContentPage {
       Content = new StackLayout {
       VerticalOptions = LayoutOptions.Center,
           Children = {
                    button,
                    image,
           },
       },
   };
}

按钮的单击处理程序调用事件ShouldTakePicture。它是一个公共成员,平台特定的代码部分将在稍后分配给它。

public event Action ShouldTakePicture = () => {};

最后,我们提供了一个公共方法来显示捕获的图像:

public void ShowImage(string filepath)
{
    image.Source = ImageSource.FromFile(filepath);
}

安卓项目

在 Android 上,我们修改MainActivity. 首先,我们为捕获的图像文件定义一个路径:

static readonly File file = new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures), "tmp.jpg");

最后,我们可以使用createdOnCreate的 static并分配一个匿名事件处理程序,它将启动一个新的用于捕获图像:InstanceAppIntent

App.Instance.ShouldTakePicture += () => {
   var intent = new Intent(MediaStore.ActionImageCapture);
   intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(file));
   StartActivityForResult(intent, 0);
};

最后但同样重要的是,我们的活动必须对生成的图像做出反应。它只会将其文件路径推送到共享ShowImage方法。

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
   base.OnActivityResult(requestCode, resultCode, data);
   App.Instance.ShowImage(file.Path);
}

就是这样!只是不要忘记在“AndroidManifest.xml”中设置“Camera”和“WriteExternalStorage”权限!

iOS 项目

对于 iOS 实现,我们创建了一个自定义渲染器。因此,我们添加一个新文件“CustomContentPageRenderer”,并在 using 语句之后添加相应的程序集属性:

[assembly:ExportRenderer(typeof(ContentPage), typeof(CustomContentPageRenderer))]

CustomContentPageRenderer继承自PageRenderer

public class CustomContentPageRenderer: PageRenderer
{
    ...
}

我们重写该ViewDidAppear方法并添加以下部分。

创建一个引用相机的新图像选择器控制器:

var imagePicker = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.Camera };

一旦ShouldTakePicture引发事件,就呈现图像选择器控制器:

App.Instance.ShouldTakePicture += () => PresentViewController(imagePicker, true, null);

拍照后保存到MyDocuments文件夹,调用共享ShowImage方法:

imagePicker.FinishedPickingMedia += (sender, e) => {
            var filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "tmp.png");
var image = (UIImage)e.Info.ObjectForKey(new NSString("UIImagePickerControllerOriginalImage"));
            InvokeOnMainThread(() => {
                image.AsPNG().Save(filepath, false);
                App.Instance.ShowImage(filepath);
            });
            DismissViewController(true, null);
        };

最后,我们需要处理取消图像拍摄过程:

imagePicker.Canceled += (sender, e) => DismissViewController(true, null);
于 2015-02-03T12:42:45.793 回答
5

试试 James Montemagno 的MediaPlugin

您可以使用Package Manager Console安装插件,只需键入并运行Install-Package Xam.Plugin.Media -Version 2.6.2,或者转到Manage NuGet Packages...并键入Xam.Plugin.Media并安装插件。(插件必须安装在您的所有项目中 - 包括客户端项目)

将提示readme.txt并按照那里的说明进行操作。之后,将以下代码(根据需要)添加到您的共享项目中。上述readme.txt文件中要遵循的说明如下。

对于安卓项目

在您的 BaseActivity 或 MainActivity(对于 Xamarin.Forms)中添加以下代码:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
    PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}  

您还必须添加一些额外的配置文件以遵守新的严格模式:

  1. 将以下内容添加到 < application > 标签内的 AndroidManifest.xml 中:

    <provider android:name="android.support.v4.content.FileProvider" 
              android:authorities="YOUR_APP_PACKAGE_NAME.fileprovider" 
              android:exported="false" 
              android:grantUriPermissions="true">
        <meta-data android:name="android.support.FILE_PROVIDER_PATHS" 
                   android:resource="@xml/file_paths"></meta-data>
    </provider>
    

    YOUR_APP_PACKAGE_NAME 必须设置为您的应用程序包名称!

  2. 在 Resources 文件夹中添加一个名为 xml 的新文件夹,并添加一个名为file_paths.xml

    添加以下代码:

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <external-path name="my_images" path="Android/data/YOUR_APP_PACKAGE_NAME/files/Pictures" />
        <external-path name="my_movies" path="Android/data/YOUR_APP_PACKAGE_NAME/files/Movies" />
    </paths>
    

    YOUR_APP_PACKAGE_NAME 必须设置为您的应用程序包名称!

对于 iOS 项目

为了访问设备的相机和照片/视频库,NSCameraUsageDescription您的应用程序需要在 Info.plist 中有密钥。NSPhotoLibraryUsageDescription如果您使用库的视频功能,那么您还必须添加NSMicrophoneUsageDescription. 当系统提示用户提供访问这些设备功能的权限时,您为每个密钥提供的字符串将显示给用户。

如:

<key>NSCameraUsageDescription</key>
<string>This app needs access to the camera to take photos.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to photos.</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app needs access to microphone.</string>

对于共享项目

要简单地打开相机,保存照片并显示带有文件路径的警报,请在共享项目中输入以下内容。

if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
    await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
    return;
}

var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
    PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
    Directory = "Sample",
    Name = "test.jpg"
});

if (file == null)
    return;

await DisplayAlert("File Location", file.Path, "OK"); 
于 2017-06-28T09:11:40.720 回答
1

这是在 Xamarin Forms 跨 Xamarin iOS 上的操作方法。

这是一个很好的开始,但它需要首先呈现一个页面,您可以在其中指定 UIApplication 为它提供用于相机/照片选择器控制器的 UIView。

https://stackoverflow.com/a/28299259/1941942

便携式项目

public interface ICameraProvider
{
    Task<CameraResult> TakePhotoAsync();
    Task<CameraResult> PickPhotoAsync();
}

private Command AttachImage 
{
    var camera = await DependencyService.Get<ICameraProvider>().TakePhotoAsync();
}

iOS 项目

[assembly: Xamarin.Forms.Dependency(typeof(CameraProvider))]

public class CameraProvider : ICameraProvider
{
    private UIImagePickerController _imagePicker;
    private CameraResult _result;
    private static TaskCompletionSource<CameraResult> _tcs;

    public async Task<CameraResult> TakePhotoAsync()
    {
        _tcs = new TaskCompletionSource<CameraResult>();

        _imagePicker = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.Camera };

        _imagePicker.FinishedPickingMedia += (sender, e) =>
        {
            _result = new CameraResult();
            var filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "tmp.png");
            var image = (UIImage)e.Info.ObjectForKey(new NSString("UIImagePickerControllerOriginalImage"));

            _result.ImageSource = ImageSource.FromStream(() => new MemoryStream(image.AsPNG().ToArray())); 
            _result.ImageBytes = image.AsPNG().ToArray();
            _result.FilePath = filepath;

            _tcs.TrySetResult(_result);
            _imagePicker.DismissViewController(true, null);
        };

        _imagePicker.Canceled += (sender, e) =>
        {
            UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null);
        };

        await UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewControllerAsync(_imagePicker, true);

        return await _tcs.Task; 
    }

    public async Task<CameraResult> PickPhotoAsync()
    {
        _tcs = new TaskCompletionSource<CameraResult>();

        _imagePicker = new UIImagePickerController
        {
            SourceType = UIImagePickerControllerSourceType.PhotoLibrary,
            MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary)
        };

        _imagePicker.FinishedPickingMedia += (sender, e) =>
        {

            if (e.Info[UIImagePickerController.MediaType].ToString() == "public.image")
            {
                var filepath = (e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl);
                var image = (UIImage)e.Info.ObjectForKey(new NSString("UIImagePickerControllerOriginalImage"));
                //var image = e.Info[UIImagePickerController.OriginalImage] as UIImage;

                _result.ImageSource = ImageSource.FromStream(() => new MemoryStream(image.AsPNG().ToArray()));
                _result.ImageBytes = image.AsPNG().ToArray();
                _result.FilePath = filepath?.Path;
            }

            _tcs.TrySetResult(_result);
            _imagePicker.DismissViewController(true, null);
        };

        _imagePicker.Canceled += (sender, e) =>
        {
            UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null);
        };

        await UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewControllerAsync(_imagePicker, true);

        return await _tcs.Task;
    }
}
于 2016-11-25T04:46:48.363 回答
0

这是在我的应用程序中运行异步相机捕获所需的:

在 iOS 中:

public async Task<string> TakePicture()
{
    if (await AuthorizeCameraUse())
    {
        var imagePicker = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.Camera };

        TaskCompletionSource<string> FinishedCamera = new TaskCompletionSource<string>();

        // When user has taken picture
        imagePicker.FinishedPickingMedia += (sender, e) => {
            // Save the file
            var filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "tmp.png");
            var image = (UIImage)e.Info.ObjectForKey(new NSString("UIImagePickerControllerOriginalImage"));
            image.AsPNG().Save(filepath, false);

            // Close the window
            UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null);

            // Stop awaiting
            FinishedCamera.SetResult(filepath);
        };

        // When user clicks cancel 
        imagePicker.Canceled += (sender, e) =>
        {
            UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null);
            FinishedCamera.TrySetCanceled();
        };

        // Show the camera-capture window
        UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(imagePicker, true, null);

        // Now await for the task to complete or be cancelled
        try
        {
            // Return the path we've saved the image in
            return await FinishedCamera.Task;
        }
        catch (TaskCanceledException)
        {
            // handle if the user clicks cancel
        }
    }

    return null;
}

如果您需要授权例程,请确保您也填写了相机用途info.plist,这是获得授权的功能:

public static async Task<bool> AuthorizeCameraUse()
{
    var authorizationStatus = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);

    if (authorizationStatus != AVAuthorizationStatus.Authorized)
    {
        return await AVCaptureDevice.RequestAccessForMediaTypeAsync(AVMediaType.Video);
    }
    else
        return true;
}

在安卓中:

private TaskCompletionSource<bool> _tcs_NativeCamera;

public async Task<string> TakePicture()
{
    _tcs_NativeCamera = new TaskCompletionSource<bool>();

    // Launch the camera activity
    var intent = new Intent(MediaStore.ActionImageCapture);
    intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(cameraCaptureFilePath));

    NextCaptureType = stype;

    StartActivityForResult(intent, SCAN_NATIVE_CAMERA_CAPTURE_ASYNC);

    // Wait here for the activity return (through OnActivityResult)
    var Result = await _tcs_NativeCamera.Task;

    // Return the camera capture file path
    return Result != Result.Canceled ? cameraCaptureFilePath : null;
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);

    switch (requestCode)
    {
        case SCAN_NATIVE_CAMERA_CAPTURE_ASYNC:
            _tcs_NativeCamera.SetResult(resultCode);
            break;
    }
}
于 2017-03-22T11:47:00.983 回答