如何将 Image 转换为 ImageSource Xamarin.Form

How to convert Image to ImageSource Xamarin.Form

嘿,我在 ZXingBarcodeImageView 中生成了图像,我想将其转换为 ImageSource,这样我就可以在 xaml 中绑定图像,如何实现,日安,谢谢

 public class GenerateCode: IGenerateCode
 {
    ZXingBarcodeImageView barcode;

    public ImageSource GenerateQr(string code)
    {
        barcode = new ZXingBarcodeImageView
        {
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.FillAndExpand,
        };
        barcode.BarcodeFormat = ZXing.BarcodeFormat.QR_CODE;
        barcode.BarcodeOptions.Width = 100;
        barcode.BarcodeOptions.Height = 100;
        barcode.BarcodeOptions.Margin = 10;
        barcode.BarcodeValue = code;
        return barcode; error as barcode is an image
    }
 }



<Image Source={Binding imgSource} />     

我假设您正在使用特定于平台的组件来生成图像。该组件要么将生成的图像存储到文件系统中,要么将 returns 二进制表示形式存储在内存中。

要将文件转换为 ImageSource,您可以使用 ImageSource.FromFile()。要转换流,请使用 ImageSource.FromStream().

您可以找到 API here and some great documentation there

在您上面的例子中,BindingContext(无论是页面还是 ViewModel 都无关紧要)将必须公开类型为 ImageSource 的 public 属性 returns 使用上述任一方法转换后的图像。

class ZXingBarcodeImageView 不会公开 ImageSource 属性 因为它是用来 而不是 Image。您可以将它放在 XAML 或 C# 中。

例如:

XAML:

<!-- this goes in your root node -->
<!-- xmlns:zxing="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms" -->

<zxing:ZXingBarcodeImageView BarcodeValue="{Binding Code}" BarcodeFormat="QR_CODE" BarcodeOptions="{Binding Options}" />

C# 后端:

protected override void OnAppearing()
{
    BindingContext = new
    {
        Code = code;
        Options = new EncodingOptions()
        {
            Width = 100,
            Height = 100,
            Margin = 10,
        }
    };
}