How To Work With Images in Xamarin Forms
Images are a crucial part of application navigation, usability, and branding. Xamarin Forms can be able to share images across all platforms, but also potentially display different images on each platform.
What we are going to learn from this article?
- Learn about what are the different methods of working with images and explaining each one in detail
- How to work with images in C# code and also in XAML
1) Image in Xamarin Forms
Xamarin Forms uses the Image
view to display images on a page. Images can be loaded from a local file, an embedded resource, or downloaded from web or server. It has two important properties
- ImageSource
- Aspect
ImageSource
ImageSource load images from local files or the Web.There are many different types of using images in Xamarin Forms.
FromFile
- Requires a filename or filepath that can be resolved on each platform.FromUri
- Requires a Uri object.FromResource
- Requires a resource identifier to an image file embedded in the applicationFromStream
- Requires a stream that supplies image data.
By using the above methods we can set different image for each platform(different image for iOS , Android and Windows) or using the same image for all platforms.
Aspect
The Aspect property determines how the image will be scaled to fit the display area:
Fill
- Stretches the image to completely and exactly fill the display area. This may result in the image being distorted.AspectFill
- Clips the image so that it fills the display area while preserving the aspect (ie. no distortion).AspectFit
- Letterboxes the image (if required) so that the entire image fits into the display area, with blank space added to the top/bottom or sides depending on whether the image is wide or tall.
2) Working with images — C# Code and Xaml
Add Resources(necessary images to Project)
- Adding Images to Main Project Solution
- I have created a new folder Assets -> Images -> Added Images inside
- To create a new folder in Solution folder refer below image:
- Adding Images to Android Project Solution
- Add or Drag your images to Resources->drawable Folder
- By adding images in drwable we can easily access it in all parts of android project
- Adding Images to iOS Project Solution
- In iOS we can also add images to Resources Folder and access it everywhere in iOS Project but I have created a new folder Images and added images in that folder .
- To create a new folder in iOS Project refer below image:
Access image FromFile
I have developed a ListView in C# code and assigned a image to ImageCell and Image from File. Find the C# code below:
C# Code
- Assigning image to ImageCell FromFile:
public class MainPage : ContentPage
{
public MainPage()
{
TableView tableViewImages = new TableView
{
HasUnevenRows = true,
Intent = TableIntent.Form,
Root = new TableRoot
{
new TableSection
{
new ImageCell
{
ImageSource = (Device.RuntimePlatform == Device.Android) ? ImageSource.FromFile("FavoriteProfile.png") : ImageSource.FromFile("Images/sports.jpg"),
Text = "ImageSource from File",
Detail = "Image is accessed using ImageSource.FromFile",
}
}
}
};this.Padding = new Thickness(10);
this.Content = tableViewImages;
}
}
- Assigning image to Image FromFile:
Image assignImageFromFile = new Image
{
Source = (Device.RuntimePlatform == Device.Android) ? ImageSource.FromFile("FavoriteProfile.png") : ImageSource.FromFile("Images/sports.jpg"),
Aspect = Aspect.AspectFit,
HeightRequest = 50,
WidthRequest = 60
};
XAML
<Image x:Name="fileImage" Aspect="AspectFit" HeightRequest="60" WidthRequest="70"/>
In Xaml, We give image a reference name and assign a image from file in Xaml.cs file
fileImage.Source = (Device.RuntimePlatform == Device.Android) ? ImageSource.FromFile("FavoriteProfile.png") : ImageSource.FromFile("Images/sports.jpg")
By accessing FromFile, we can set image for a specific platform or Set image for both platform. It’s up to developer’s choice.
Access image From Source
I have developed a ListView in C# code and assigned a image to ImageCell and Image from Source directly. Find the C# code below:
C# Code
- Assigning image to ImageCell From Source:
public class MainPage : ContentPage
{
public MainPage()
{
TableView tableViewImages = new TableView
{
HasUnevenRows = true,
Intent = TableIntent.Form,
Root = new TableRoot
{
new TableSection
{
new ImageCell
{
ImageSource = "icon.png",
Text = "Image from Source",
Detail = "Image is accessed from Source",
}
}
}
};
this.Padding = new Thickness(10);
this.Content = tableViewImages;
}
}
- Assigning image to Image From Source:
Image assignImageFromSource = new Image
{
Source = "icon.png",
Aspect = Aspect.AspectFit,
HeightRequest = 50,
WidthRequest = 60
};
XAML
<Image Source="icon.png"/>
We have image named icon.png in both Android and iOS Project Solution ,to access image in both directory we can use FromSource.
Access image FromResource
I have developed a ListView in C# code and assigned a image to ImageCell and Image from Resource.
Before we assign a image from Resource, we need to make sure the images are set a EmbeddedResource in Build Action . Refer a below image to set a image as a embeddedResource.
Find the C# code below to assign image FromResource:
C# Code
- Assigning image to ImageCell FromResource:
public class MainPage : ContentPage
{
public MainPage()
{
TableView tableViewImages = new TableView
{
HasUnevenRows = true,
Intent = TableIntent.Form,
Root = new TableRoot
{
new TableSection
{
new ImageCell
{
ImageSource = ImageSource.FromResource("Images.Assets.Images.NormalProfile.png"),
Text = "ImageSource from Resource",
Detail = "Image is accessed using ImageSource.FromResource",
},
}
}
};this.Padding = new Thickness(10);
this.Content = tableViewImages;
}
}
- Assigning image to Image FromResource:
Image assignImageFromResource = new Image
{
Source = ImageSource.FromResource("Images.Assets.Images.NormalProfile.png"),
Aspect = Aspect.AspectFit,
HeightRequest = 50,
WidthRequest = 60
};
XAML
<Image x:Name="resourceImage" Aspect="AspectFit" HeightRequest="60" WidthRequest="70"/>
In Xaml, We give image a reference name and assign a image from file in Xaml.cs file
resourceImage.Source = ImageSource.FromResource("Images.Assets.Images.NormalProfile.png");
By accessing FromResource, we need to specify a image’s path.This path will vary depending on where your image is placed in the project.
Access image FromFile
I have developed a ListView in C# code and assigned a image to ImageCell and Image from File. Find the C# code below:
C# Code
- Assigning image to ImageCell FromFile:
public class MainPage : ContentPage
{
public MainPage()
{
TableView tableViewImages = new TableView
{
HasUnevenRows = true,
Intent = TableIntent.Form,
Root = new TableRoot
{
new TableSection
{
new ImageCell
{
ImageSource = (Device.RuntimePlatform == Device.Android) ? ImageSource.FromFile("FavoriteProfile.png") : ImageSource.FromFile("Images/sports.jpg"),
Text = "ImageSource from File",
Detail = "Image is accessed using ImageSource.FromFile",
}
}
}
};this.Padding = new Thickness(10);
this.Content = tableViewImages;
}
}
- Assigning image to Image FromFile:
Image assignImageFromFile = new Image
{
Source = (Device.RuntimePlatform == Device.Android) ? ImageSource.FromFile("FavoriteProfile.png") : ImageSource.FromFile("Images/sports.jpg"),
Aspect = Aspect.AspectFit,
HeightRequest = 50,
WidthRequest = 60
};
XAML
<Image x:Name="fileImage" Aspect="AspectFit" HeightRequest="60" WidthRequest="70"/>
In Xaml, We give image a reference name and assign a image from file in Xaml.cs file
fileImage.Source = (Device.RuntimePlatform == Device.Android) ? ImageSource.FromFile("FavoriteProfile.png") : ImageSource.FromFile("Images/sports.jpg")
By accessing FromFile, we can set image for a specific platform or Set image for both platform. It’s up to developer’s choice.
Access image From Uri
I have developed a ListView in C# code and assigned a image to ImageCell and Image from Source directly. Find the C# code below:
C# Code
- Assigning image to ImageCell From Source:
public class MainPage : ContentPage
{
public MainPage()
{
TableView tableViewImages = new TableView
{
HasUnevenRows = true,
Intent = TableIntent.Form,
Root = new TableRoot
{
new TableSection
{
new ImageCell
{
ImageSource = ImageSource.FromUri(new Uri("https://image.shutterstock.com/image-photo/bright-spring-view-cameo-island-600w-1048185397.jpg")),
Text = "ImageSource from Uri",
Detail = "Image is accessed using ImageSource.FromUri",
}
}
}
};
this.Padding = new Thickness(10);
this.Content = tableViewImages;
}
}
- Assigning image to Image From Source:
Image assignImageFromUri = new Image
{
Source = ImageSource.FromUri(new Uri("https://image.shutterstock.com/image-photo/bright-spring-view-cameo-island-600w-1048185397.jpg")),
Aspect = Aspect.AspectFit,
HeightRequest = 50,
WidthRequest = 60
};
XAML
<Image Source="https://image.shutterstock.com/image-photo/bright-spring-view-cameo-island-600w-1048185397.jpg"
Aspect="AspectFit" HeightRequest="{OnPlatform iOS=200, Android=150}"
WidthRequest="{OnPlatform iOS=200, Android=150}" HorizontalOptions="Center"/>
By access FromUri, we can use link to load a image to Image or ImageCell.
Image Caching
A UriImageSource
also supports caching of downloaded images, configured through the following properties:
CachingEnabled
– Whether caching is enabled (true
by default).CacheValidity
– ATimeSpan
that defines how long the image will be stored locally.
Caching is enabled by default and will store the image locally for 24 hours. To disable caching for a particular image, instantiate the image source as follows:
imageRefernceName.Source = new UriImageSource { CachingEnabled = false, Uri="http://server.com/image" };
To set a specific cache period (for example, 2 days) instantiate the image source as follows:
imageFromWeb.Source = new UriImageSource
{
Uri = new Uri("https://xamarin.com/content/images/pages/forms/example-app.png"),
CachingEnabled = true,
CacheValidity = new TimeSpan(2,0,0,0)
};
Built-in caching makes it very easy to support scenarios like scrolling lists of images, where you can set (or bind) an image in each cell and let the built-in cache take care of re-loading the image when the cell is scrolled back into view.instantiate the image source as follows:
Access image From Stream
Requires a stream that supplies image data to assign it to images
4) Conclusion and Resources
Now you know how to work with images in Xamarin Forms, set images for specific platforms,etc.Find the code and material for this article in this github link.You can refer the Github link incase you have queries.
If you run the project which I have mentioned above you will get screen as below:
I hope you found this article helpful. If you did, please don’t hesitate to clap or share this post on Twitter or your social media of choice, every share helps me to write more. If you have any queries, feel free to comment below and I’ll see what I can do.Thanks.