简体   繁体   中英

MVVMCross Xamarin binding to a bitmap with converter

I have a working BindableViewPager (thanks to Cheesebaron!) and within the viewpager control I have a bitmap for each paged item. My viewmodel for the viewpager includes

    private double _bearing;
    public double Bearing
    {
        get { return _bearing; }
        set
        {
            _bearing = value;
            RaisePropertyChanged(() => Bearing);
        }
    }

The intention is to dynamically create a bitmap to be an image that reflects the angle of the bearing. So I bind my ImageView to the bearing with a value converter:

<ImageView
    ...
    local:MvxBind="Bitmap Bearing, Converter=BearingToImage" />



public class BearingToImageConverter : MvxValueConverter<double, byte[]>
{

    protected override byte[] Convert(double value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        Bitmap bmp = BitmapFactory.DecodeResource(Application.Context.ApplicationContext.Resources, Resource.Drawable.direction_pointer_black_bg);
        byte[] bitmapData;
        using (var stream = new MemoryStream())
        {
            bmp.Compress(Bitmap.CompressFormat.Png, 100, stream);
            bitmapData = stream.ToArray();
        }

        return bitmapData;
    }
}

There's a couple of lines of code using a matrix to do the rotation which I've omitted for clarity since the code doesn't work without it either.

When running the code, the converter is called but I get a warning:

MvxBind:Warning: 54.71 Value was not be a valid Bitmap

and no image is shown. Looking at the PictureTaking example, I see that the binding is done directly against a byte array with an InMemoryImage converter. Is it valid to attempt to bind in the way I have done and if I need to use my own converter, do I need to do more to emulate the InMemoryImage conversion?

Resolved , and apologies for bad etiquette in answering my own question, but for future reference:

The issue seems to be the missing InMemoryImage converter. Rather than having my converter return a byte[], I now return an object, that being the bitmap itself.

So the converter signatures become:

public class BearingToImageConverter : MvxValueConverter<double, object> { ...

protected override object Convert(double value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { ////

where the returned object is a Bitmap.

As I know you can bind the array of bytes to the ImageView but not double, so that's why you have that warning. And I guess that's why your custom value converter didn't invoke at all.

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