Adding images to your app requires two steps: first, add the images to your project; then add controls and code to display them on a screen. Refer to the Working with Images article for more detailed coverage of image handling in Xamarin.iOS.
Images can be added to any folder in your Xamarin Studio solution, and if the Build Action is set to Content then the file will be included with your app and can be displayed.
Xamarin Studio also supports a special directory called Resources that can also contain image files. Files in the Resources folder should have the Build Action set to BundleResource.
This screenshot shows the Build Action options when a file is right-clicked:
Xamarin Studio will typically choose the correct Build Action automatically but you should be aware of these settings, especially if you move files around in your project.
To add an image file to your project, first right-click the project and choose Add Files...
Select the image (or images) you wish to include in the standard file dialog. The default build action for images will be BundleResource – don’t override this value unless you have a specific reason.
The image will be added to your project and available to be loaded and displayed in code. This screenshot shows an image added to an iOS application project:
Files placed in the Resources directory are treated differently from regular files – the contents of the Resources folder are copied to the root of the application and can be referenced from there in your code. This can be useful for many reasons:
The Resources directory is especially useful in a Library project, since the code can assume that those images will be copied into the root of the consuming application, making it easier to write shared code libraries that require image, sound, video, XML or other files.
The Resources directory must be so named, and all files should have the Build Action set to BundleResource. This screenshot shows the image file blocks.jpg with the correct build action set:
Because blocks.jpg
is located in the root of the Resources directory it will be available at runtime in the application bundle’s root. To display this image in an ImageView control use the following code:
imageview1.Image = UIImage.FromBundle ("blocks.jpg");
If we had placed the image in /Resources/Pics/blocks.jpg
then the code would include the Pics folder in the path:
imageview1.Image = UIImage.FromBundle ("Pics/blocks.jpg");
Resource file references never need to include the Resources
folder.