0
点赞
收藏
分享

微信扫一扫

Xamarin.Forms 引用 放在 PCL 中的图片


今天状态及其不好,见谅,Xamarin 技术交流 (偏向 xamarin.android): 1092417123

PCL 中图片资源格式

官方解释 : Embedded Images

Embedded images are also shipped with an application (like local images) but instead of having a copy of the image in each application’s file structure the image file is embedded in the assembly as a resource. This method of distributing images is particularly suited to creating components, as the image is bundled with the code.

To embed an image in a project, right-click to add new items and select the image/s you wish to add. By default the image will have Build Action: None; this needs to be set to Build Action: EmbeddedResource.

Image 设置

beach.jpg 是图片名称

<ContentPage.Content>
<StackLayout>
<Label Text = " Embedded Images
<Image Source = "{local:ImageResource WorkingWithImages.beach.jpg}" />
</StackLayout>
</ContentPage.Content>

代码中 :

var embeddedImage = new Image { Source = ImageSource.FromResource("WorkingWithImages.beach.jpg") };

Using XAML

Because there is no built-in type converter from string to ResourceImageSource, these types of images cannot be natively loaded by XAML. Instead, a simple custom XAML markup extension can be written to load images using a Resource ID specified in XAML :

// You exclude the 'Extension' suffix when using in Xaml markup
[Preserve(AllMembers = true)]
[ContentProperty ("Source")]
public class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }

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

// Do your translation lookup here, using whatever method you require
string s = Application.Current.Resources["logoEvo"] as string;

var assembly = typeof(ImageResourceExtension).GetTypeInfo().Assembly;
var assemblyString = assembly.GetName().Name.ToString();
var imageSource = ImageSource.FromResource(assemblyString + "." + s);
return

在 App.xaml 中定义 string,以便之后引用

<Application.Resources>
<ResourceDictionary>
<x:String x:Key="logoEvo">beach.jpg</x:String>
</ResourceDictionary>
</Application.Resources>

Page 中使用

<Image Source="{local:ImageResourceExtension logoEvo}"

Troubleshooting Embedded Images

Because it is sometimes difficult to understand why a particular image resource isn’t being loaded, the following debug code can be added temporarily to an application to help confirm the resources are correctly configured. It will output all known resources embedded in the given assembly to the Console to help debug resource loading issues.

using System.Reflection;
// ...
// NOTE: use for debugging, not in released app code!
var assembly = typeof(EmbeddedImages).GetTypeInfo().Assembly;
foreach (var res in assembly.GetManifestResourceNames())
{
System.Diagnostics.Debug.WriteLine("found resource: "

88, 调整心态


举报

相关推荐

0 条评论