单击按钮时如何从库中选择图像(Xamarin iOS)

时间:2017-01-13 06:04:21

标签: ios xamarin uiimagepickercontroller

我看过这段代码: 遗憾的是,https://developer.xamarin.com/recipes/ios/media/video_and_photos/choose_a_photo_from_the_gallery/会立即加载图库,而不会考虑让用户先选择。

我试图给用户两个选项:

1 - 拍照 2 - 从图库中选择现有照片

这两个都是你点击的按钮。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是显示带有Prism.IPageDialogService的ActionSheet,以便为用户提供选择。你甚至可以做这样的事情来获得跨平台的解决方案:

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();
    }
}

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;
}

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;
}

如果你想要两个按钮而不是一个按钮,则不需要Prism.IPageDialogService,你可以将方法TakePhoto()PickPhoto()绑定到两个不同的按钮。