Reputation: 2543
I follow the guide on the official Xamarin website telling how to embed the image into the cross-platform app. I build the app only for Android platform.
Unfortunately, the image is not shown during debug on my Sony D5803 Z3 Compact or in Android 7.1 emulator. I use VS 2017 RC on Windows 10. All the previous HelloWorld apps e.g. with downloading the picture via URI worked well on my phone.
I would be grateful for any help or advice how to troubleshoot the problem.
The image picture.jpg
has set the build property embedded resource
(in Polish Akcja kompilacji: osadzony zasób
)
I can see the images in the debug folder as shown in the screenshot
This is the XAML page I use to show the image:
ImageEmbeddedPAge.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:markupExtensions="clr-namespace:HelloWorld.MarkupExtensions;assembly=HelloWorld.Droid"
x:Class="HelloWorld.ImageEmbeddedPAge">
<StackLayout HorizontalOptions="Center"
VerticalOptions="Center">
<Image x:Name="image"
Source="{markupExtensions:ImageResource Source=HelloWorld.Images.picture.jpg}"/>
</StackLayout>
</ContentPage>
ImageResourceExtension.cs in folder MarkupExtensions
namespace HelloWorld.MarkupExtensions
{
[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
var imageSource = ImageSource.FromResource(Source);
return imageSource;
}
}
}
App.xaml.cs
namespace HelloWorld
{
public partial class App : Application
{
public App ()
{
InitializeComponent();
MainPage = new ImageEmbeddedPAge();
}
}
}
Upvotes: 1
Views: 659
Reputation: 16652
Totally agree with @Cheesebaron, since you created a Xamarin.Forms shared projecrt, we need to place resolution images in specially-named directories in Android project, these specially-named directories are all placed under the Resources
-> Drawable
folder in the Android project.
If you want to use an embedded image, we need to use a Portable Lib for each platfrom, or just create a Xamarin.Forms portable project. If you want to create a PCL by yourself, than please be careful with the targets of this PCL, normally it should be like following image so can it be used for different platforms:
And finally to embed an image in a project, by default the image will have Build Action: None
, please set it to Build Action: EmbeddedResource
.
The reason why we cannot place images in a shared project is that:
The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.
The images then are treated as files not resources.
Upvotes: 1