在另一个文件夹中添加图像而不是在 xamarin 跨平台中可绘制 [英] add image in another folder instead of drawable in xamarin cross-platforms

查看:18
本文介绍了在另一个文件夹中添加图像而不是在 xamarin 跨平台中可绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用

<image source="live.png"/>

但我不知道如何从我在 Resource 中创建的其他文件夹中获取图像有人可以帮我吗?

But i don't know how to get image from other folder i create in Resource Can somebody help me?

推荐答案

Android 对放置图像的位置非常挑剔,因此最好的办法是将图像存储在公共项目中.在此示例中,我假设标准 Xamarin.Forms 解决方案包含以下项目:Foo、Foo.Android、Foo.IOS 和 Foo.UWP.你的显然会有不同的名字,所以你必须替换 Foos...

Android is very picky about where you can put images, so your best bet is to store your images in the common project. In this example I assume a standard Xamarin.Forms solution with the following projects: Foo, Foo.Android, Foo.IOS and Foo.UWP. Yours will obviously have different names, so you'll have to substitute the Foos...

以下所有代码都会进入公共代码项目,Foo.

All the following code will go into the common code project, Foo.

首先,创建一个名为 Extensions 的新文件夹(只是为了保持代码整洁)并向其中添加以下类:

First, create a new folder called Extensions (just to keep your code tidy) and add the following class to it:

[ContentProperty(nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
    public string Source { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Source == null)
        {
            return null;
        }

        var imageSource = ImageSource.FromResource(Source);

        return imageSource;
    }
}

现在将此类的命名空间添加到您的标记中:

Now add the namespace for this class to your markup:

xmlns:extensions="clr-namespace:Foo.Extensions"

接下来,再次在您的公共项目中,而不是在您的 Android 项目中,为您的图像创建一个文件夹.您也可以创建子文件夹.添加您的图像并确保每个图像的构建操作设置为 Embedded Resource.

Next, create a folder for your images, again in your common project, NOT in your Android project. You can create subfolders as well. Add your images and make sure that the build action for each image is set to Embedded Resource.

现在您可以像这样在 XAML 中引用这些图像:

Now you can reference those images in your XAML like this:

<Image Source="{extensions:ImageResource Foo.Images.Subfolder.Bar.png}">

请注意,您需要提供图像的完整路径,包括项目名称(在本例中为 Foo),并且文件夹以点分隔,而不是斜线.

Note that you need to supply the full path of the image, including the project name (Foo in this case) and that folders are separated by dots, not slashes.

这篇关于在另一个文件夹中添加图像而不是在 xamarin 跨平台中可绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆