0

我构建了一个 Xamarin 应用程序:Android,并试图让用户能够设置头像。使用 Xamarin Essentials Media Picker 我正在尝试捕获图像或选择一个图像。但是每次应用程序运行任何一种方法时,它都会运行,然后在选择或捕获图像之前使应用程序崩溃。有趣的是它有时有效,但几乎没有。

我尝试了很多方法来弄清楚发生了什么,但是没有实际的错误可以使用,我一无所获。

我正在使用 MVVM 设计模式。我的代码:

    private async Task TakePicture()
    {
        try
        {
            var photo = await MediaPicker.PickPhotoAsync(); 
            if (photo != null)
            {
                await App.UserManager.UpdateAvatarAsync(photo);
                RenderImages();
            }
        }
        catch (global::System.Exception ex)
        {
            await AppShell.Current.DisplayAlert("Oops", "Something went wrong and its not your fault", "Okay");
        }

    }
4

1 回答 1

1

您可以使用以下方法来挑选照片。

1. 使用Xam.Plugin.Media. 您可以从 NuGet 安装。不要忘记检查您保存照片的位置并请求运行时权限。

下面的代码显示了如何从相机中选择照片并设置为图像控件。

  pickPhoto.Clicked += async (sender, args) =>
  {
    if (!CrossMedia.Current.IsPickPhotoSupported)
    {
      DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
      return;
    }
     var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
                  {
                      PhotoSize =  Plugin.Media.Abstractions.PhotoSize.Medium,
                
                  });


    if (file == null)
      return;

    image.Source = ImageSource.FromStream(() =>
    {
      var stream = file.GetStream();
      file.Dispose();
      return stream;
    });
  };

在此处输入图像描述

2.使用依赖服务。

[assembly: Dependency(typeof(PhotoPickerService))]
namespace DependencyServiceDemos.Droid
{
public class PhotoPickerService : IPhotoPickerService
{
    public Task<Stream> GetImageStreamAsync()
    {
        // Define the Intent for getting images
        Intent intent = new Intent();
        intent.SetType("image/*");
        intent.SetAction(Intent.ActionGetContent);

        // Start the picture-picker activity (resumes in MainActivity.cs)
        MainActivity.Instance.StartActivityForResult(
            Intent.CreateChooser(intent, "Select Photo"),
            MainActivity.PickImageId);

        // Save the TaskCompletionSource object as a MainActivity property
        MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<Stream>();

        // Return Task object
        return MainActivity.Instance.PickImageTaskCompletionSource.Task;
    }
}
}

在此处输入图像描述

您可以从下面的链接下载源文件。https://docs.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/dependencyservice/

于 2021-01-07T06:33:09.997 回答