繁体   English   中英

如何将 Image.Source 获取为字符串

[英]How to get Image.Source as string

在 Xamarin 中设置图像的来源很容易

using Xamarin.Forms;
Image image = new Image;
image.Source = "someImage.jpg";

但是我不能做反向操作。
例如:给定一个已经设置了来源的图像,打印来源。

Console.WriteLine ("Print Image source ==> {0}",image.Source);
Console.WriteLine ("Print Image source ==> {0}",image.Source.ToString());

...以及一些不连贯的组合。

谁能告诉我如何从图像中获取源代码(带有字符串)。

Xamarin.Forms Image.Source属性的类型为ImageSource

Xamarin.Forms中的ImageSource有一些继承此类的类,如: -

  • FileImageSource
  • StreamImageSource
  • UriImageSource

您可以键入检查 Image.Source以查看Image.Source中正在使用的实现 ,然后转换 ,并访问已转换对象的属性。

例如(假设ImageSourceFileImageSource ),您将拥有如下内容: -

Xamarin.Forms.Image objImage;
..
..

..
if (objImage.Source is Xamarin.Forms.FileImageSource)
{
    Xamarin.Forms.FileImageSource objFileImageSource = (Xamarin.Forms.FileImageSource)objImage.Source;
    //
    // Access the file that was specified:-
    string strFileName = objFileImageSource.File;
}

它看起来像Xamarin.Forms.Image有一个类型为Xamarin.Forms.ImageSourceSource属性,它有一个来自string的隐式转换。 这就是为什么你可以做Image.Source = "someImage.jpg" ,但它没有办法回去,可能是因为它只使用字符串来查找文件并加载它。 如果您需要加载文件的名称,则必须自己跟踪它。

private async void myImage_Tapped(object sender, EventArgs e)
    {
        try
        {
            var url = ((sender as Image).Source as UriImageSource).Uri.AbsoluteUri;
            await Navigation.PushPopupAsync(new WebView_Page(url));
        }
        catch (Exception ex)
        {
            //await DisplayAlert("!", ex.Message, "OK");
        }
    }

或者像这样使用

var url = (myImage.Source as UriImageSource).Uri.AbsoluteUri;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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