简体   繁体   中英

How to select an image from gallery when clicking a button (Xamarin iOS)

I've taken a look at this code snippet: https://developer.xamarin.com/recipes/ios/media/video_and_photos/choose_a_photo_from_the_gallery/ unfortunately this loads the gallery immediately and doesn't take into consideration giving the user an option to select first.

I'm trying to give the user two options:

1 - take a photo 2 - choose an existing photo from gallery

Both of these would be buttons you click on. Any ideas?

One way to do it is to display an ActionSheet with Prism.IPageDialogService to give choices to the user. You can even do something like this to have a cross-platform solution:

private async void AddImage() // This is your method for your button
{
    string chosen = await _dialogService.DisplayActionSheetAsync("Which source do you want to use?", "Cancel", null, "Camera", "Galery");
    if (chosen == "Camera")
    {
        TakePhoto();
    }
    else if (chosen == "Galery")
    {
        PickPhoto();
    }
}

Implementation of TakePhoto() :

private async void TakePhoto()
{
    await CrossMedia.Current.Initialize();

    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
    {
        await _dialogService.DisplayAlertAsync("Warning", "Camera not available", "OK");
        return;
    }

    _mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
    {
        SaveToAlbum = true,
        Directory = "Sample",
        Name = "sample" + DateTime.Now.ToLocalTime().ToString("yyyyMMddHHmmss") + ".jpg"
    });

    if (_mediaFile == null)
    {
        return;
    }

    ImageButtonAddGroup = _mediaFile.Path;
}

Implementation of PickPhoto() :

private async void PickPhoto()
{
    await CrossMedia.Current.Initialize();

    if (!CrossMedia.Current.IsPickPhotoSupported)
    {
        await _dialogService.DisplayAlertAsync("Warning", "Camera not available", "OK");
        return;
    }

    _mediaFile = await CrossMedia.Current.PickPhotoAsync();
    if (_mediaFile == null)
    {
        return;
    }
    ImageButtonAddGroup = _mediaFile.Path;
}

If you want two buttons instead of one, you don't need the Prism.IPageDialogService and you can just bind the methods TakePhoto() and PickPhoto() to two different buttons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM