Skip To Content ArcGIS for Developers Sign In Dashboard

ArcGIS Runtime SDK for .NET

Text Symbols

Download Samples Repository

Description

Sample shows how to create Text Symbols (TextSymbol) and add graphics using the symbols.

"Desktop" "Store" "Phone" Available for Desktop, Store, Phone

Sample Code

<UserControl x:Class="ArcGISRuntime.Samples.Desktop.TextSymbols"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:ArcGISRuntime.Samples.Desktop"
             xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013">
    <Grid x:Name="layoutGrid">
        <esri:MapView x:Name="MyMapView" WrapAround="True">
			<esri:Map InitialViewpoint="-15053000,2749000,-6540000,6590000">
				<esri:ArcGISTiledMapServiceLayer
                    ServiceUri="http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer" />
			</esri:Map>
			<esri:MapView.GraphicsOverlays>
				<esri:GraphicsOverlay x:Name="graphicsOverlay" />
			</esri:MapView.GraphicsOverlays>
		</esri:MapView>

        <Border Background="White" BorderBrush="Black" BorderThickness="1" Margin="30" Padding="20"
                HorizontalAlignment="Right" VerticalAlignment="Top">
            <StackPanel>
                <TextBlock Text="Click the map to add points with the selected text symbol."
                           FontSize="14" Width="250" TextAlignment="Left" TextWrapping="Wrap" />

                <StackPanel HorizontalAlignment="Stretch" Margin="12,20,12,0">
                    <ComboBox x:Name="symbolCombo" SelectedIndex="0" SelectionChanged="symbolCombo_SelectionChanged"
                              VerticalContentAlignment="Center">
                        <ComboBox.ItemTemplate>
                            <DataTemplate>
                                <Image Source="{Binding}" Stretch="None" />
                            </DataTemplate>
                        </ComboBox.ItemTemplate>
                    </ComboBox>
                </StackPanel>
            </StackPanel>
        </Border>

        <Border Background="White" BorderBrush="Black" BorderThickness="2" Margin="30"
                HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="Hidden">
        </Border>
    </Grid>
</UserControl>
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Layers;
using Esri.ArcGISRuntime.Symbology;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ArcGISRuntime.Samples.Desktop
{
	/// <summary>
	/// Sample shows how to create Text Symbols (TextSymbol) and add graphics using the symbols.
	/// </summary>
	/// <title>Text Symbols</title>
	/// <category>Symbology</category>
	public partial class TextSymbols : UserControl
	{
		private Random _random = new Random();
		private List<TextSymbol> _symbols;

		/// <summary>Construct Text Symbols sample control</summary>
		public TextSymbols()
		{
			InitializeComponent();

			MyMapView.ExtentChanged += MyMapView_ExtentChanged;
		}

		// Start map interaction
		private async void MyMapView_ExtentChanged(object sender, EventArgs e)
		{
			MyMapView.ExtentChanged -= MyMapView_ExtentChanged;

			await SetupSymbolsAsync();
			DataContext = this;

			await AcceptPointsAsync();
		}

		// Cancel current shape request when the symbol selection changes 
		private async void symbolCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (MyMapView.Editor.IsActive)
				MyMapView.Editor.Cancel.Execute(null);

			await AcceptPointsAsync();
		}

		// Accept user map clicks and add points to the graphics layer with the selected symbol
		private async Task AcceptPointsAsync()
		{
			try
			{
				while (MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry.Extent != null)
				{
					var point = await MyMapView.Editor.RequestPointAsync();

					var symbol = _symbols[symbolCombo.SelectedIndex];
					graphicsOverlay.Graphics.Add(new Graphic(point, symbol));
				}
			}
			catch (TaskCanceledException)
			{
			}
			catch (Exception ex)
			{
				MessageBox.Show("Error: " + ex.Message, "Text Symbols");
			}
		}

		// Create text symbols - text for the symbol is the name of the font but could be anything
		private async Task SetupSymbolsAsync()
		{
			try
			{
				var fontFamilies = new List<string>()
				{
					"Bogus", "Algerian", "Chiller", "Comic Sans MS",
					"Cooper", "Elephant", "Forte", "Jokerman",
					"Lindsey", "Mistral", "Motorwerk", "Old English Text MT",
					"Parchment", "Ravie", "Script MT", "Segoe Print",
					"Showcard Gothic", "Snap ITC", "Vivaldi", "Wingdings"
				};

                // Check what fonts are installed and remove ones that aren't
                var notFoundFonts = fontFamilies.Where(f => !Fonts.SystemFontFamilies.Any(fs => fs.Source == f)).ToList();
                foreach (var notInstalledFont in notFoundFonts)
                    fontFamilies.Remove(notInstalledFont);

                // Create symbols from font list
                _symbols = fontFamilies
                    .Select(f => new TextSymbol()
                    {
                        Text = f,
                        Color = GetRandomColor(),
                        HorizontalTextAlignment = HorizontalTextAlignment.Center,
                        VerticalTextAlignment = VerticalTextAlignment.Bottom,
                        Font = new SymbolFont(f, 20)
                    })
                    .ToList();

				// Create image swatches for the UI
				Task<ImageSource>[] swatchTasks = _symbols
					.Select(sym => sym.CreateSwatchAsync(200, 30, 96, Colors.Transparent))
					.ToArray();

				symbolCombo.ItemsSource = new List<ImageSource>(await Task.WhenAll(swatchTasks));
			}
			catch (Exception ex)
			{
				Debug.WriteLine("Error: " + ex.Message);
			}
		}

		// Utility function: Generate a random System.Windows.Media.Color
		private Color GetRandomColor()
		{
			var colorBytes = new byte[3];
			_random.NextBytes(colorBytes);
			return Color.FromRgb(colorBytes[0], colorBytes[1], colorBytes[2]);
		}
	}
}
Feedback on this topic?