Another common application for icons are toolbar items. As a small example we create an empty label
var label = new Label {
Text = "",
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
};
and add it to the MainPage:
MainPage = new NavigationPage(new ContentPage { Content = label });
Now we add two toolbar items. The first one has an Icon and will write “Xamarin!” on the label. Note that a toolbar icon refers to platform-specific local images, requiring us to specify filenames.
MainPage.ToolbarItems.Add(new ToolbarItem {
Icon = Device.OS == TargetPlatform.iOS ? "Icon-Small.png" : "xamarin.png",
Command = new Command(() => label.Text = "Xamarin!"),
});
On iOS we need to have a correctly sized icon available. Since we already added the Xamarin logo as an app icon, the 29-pixel version and the 58-pixel versions are located in the “Resources” folder named “Icon-Small.png” and “[email protected]”. The latter with the “2@x” suffix is automatically used for retina displays. For different icons you need to prepare such images yourself and add them to the “Resources” folder with the same naming scheme “your_icon.png” and “[email protected]”.
Another thing to consider is that iOS allows unicolored toolbar icons only. More specifically, there must be one color on a transparent background, while all colored pixels will be rendered blue. In our example there is a blue hexagon with a white “X” on a transparent background. Both, the hexagon and the “X” are rendered blue. Only the transparent background vanishes. Thus, when creating an icon set for an app, we need to consider these limitations.
On Android, the icon is automatically scaled and displayed with all its colors. For this reason – and the different design guides – it is essential to create separate icon sets for each platform.
The second toolbar item is plain text and, consequently, straight forward. Instead of specifying the Icon, we define a Text. When clicked, the label will display the string “Forms!”.
MainPage.ToolbarItems.Add(new ToolbarItem {
Text = "Forms",
Command = new Command(() => label.Text = "Forms!"),
});