Set Image Source on return from Gallery/Camera?

1.4k Views Asked by At

I have an Image view I'm having trouble setting the source for. I'm using a button to execute a TakePictureCommand which calls the TakePicture() method (shown below) which in turn sets my source "ImageSource". Debugging the method shows the image is coming in, but I never see it come up in the UI.

I may not be setting the binding for the Image properly, this is what I have:

Image avatar = new Image();
avatar.Source = ImageSource;

Button setImageBtn = new Button{ Text = "Photo" };
setImageBtn.Clicked += async (sender, e) =>
{
    string action = await DisplayActionSheet(
           "Event Photo", "Cancel", null, OPTION_CAMERA, OPTION_GALLERY);

    if(action == OPTION_CAMERA) {
        TakePictureCommand.Execute(null);
    }

    else if(action == OPTION_GALLERY) {
        SelectPictureCommand.Execute(null);
    }
};

TakePicture()

private async Task<MediaFile> TakePicture()
{
    Setup();

    ImageSource = null;

    return await _mediaPicker.TakePhotoAsync(
        new CameraMediaStorageOptions { 
            DefaultCamera = CameraDevice.Front, 
            MaxPixelDimension = 400 
    }).ContinueWith(t =>
    {
        if (t.IsFaulted)
        {
            Status = t.Exception.InnerException.ToString();
        }
        else if (t.IsCanceled)
        {
            Status = "Canceled";
        }
        else
        {
            var mediaFile = t.Result;

            ImageSource = ImageSource.FromStream(() => mediaFile.Source);

            return mediaFile;
        }

        return null;
    }, _scheduler);
}

What am I missing here?

1

There are 1 best solutions below

0
On

Below approach is working for me:

First, in XAML I added Image view

<Image Source="{Binding ImageSource}" VerticalOptions="Fill" HorizontalOptions="Fill"
                    Aspect="AspectFit"/>

Second, in ViewModel I added ImageSource property like this:

public ImageSource ImageSource
{
    get { return _imageSource; }
    set { this.SetProperty(ref _imageSource, value); }
}

Third, in command handler:

await TakePicture ();

Forth, code of TakePicture() method the same as you wrote. My Setup():

if (_mediaPicker != null)
            return;
var device = Resolver.Resolve<IDevice>();
_mediaPicker = DependencyService.Get<IMediaPicker>() ?? device.MediaPicker;