Setting an image in your Xamarin.Forms project is easily done when setting the image as embedded resource since 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. According to this documentation, it is done easily as follows:
1 | var embeddedImage = new Image { Source = ImageSource.FromResource("ImagesProj.beach.jpg") }; |
I succeeded in adding images into my Xamarin.Forms projects using this method a while ago on earlier versions of Xamarin.Forms. But recently, I got an issue when trying this again on Xamarin.Forms 2.5.0.280555 and .Net standard 2.0 as my shared project. This issue was System.Reflection.TargetException. This was a pain in the ?. But, it wasn’t that difficult to resolve.
Don’t miss any post and subscribe to the mailing list
[zc4wp_za2]
After researching online, I found a solution. What you need to do is call the image as follows:
1 2 | var assembly = typeof(TypeInProjectAssembly).Assembly; Img.Source = ImageSource.FromResource(@"Project.Images.Image.png", assembly) |
Where TypeInProjectAssembly is any type in your current project’s assembly. and Project.Images.Image.png refers to the Default namespace of the project and the file path separated by periods (.).
From here, you may have resolved you issue already, but don’t forget, the image should have a buld action of Embedded resource.
After doing all this, I though the problem would have been resolved by now but, when running the project on its different platforms, I noticed the image wasn’t displyaed. If this happen’s to you, open your .csproj file in edit mode. Check if your image was correctly added as embedded resource and check LogicalName attribute, if it is present or if it matches what you have in your code (in my case this value is Project.Images.Image.png). If it doesn’t match or it is not present, add it your self as follows:
1 2 3 4 5 | <ItemGroup> <EmbeddedResource Include="Images\Image.png"> <LogicalName>Project.Images.Image.png</LogicalName> </EmbeddedResource> </ItemGroup> |
After doing all this, you should have resolved this issue.
[zc4wp_za2]
Follow me on social media and stay updatedIf you find this article useful, please follow me on Twitter, Github, Linkedin, or like my Facebook page to stay updated.
Check how to build a simple android camera app with Xamarin.Android here.
Follow me on social media and stay updated