XAML-Map-Control/MapControl/GlyphRunText.cs

73 lines
2.5 KiB
C#
Raw Normal View History

// XAML Map Control - http://xamlmapcontrol.codeplex.com/
2015-01-20 17:52:02 +01:00
// © 2015 Clemens Fischer
2012-05-04 12:52:20 +02:00
// Licensed under the Microsoft Public License (Ms-PL)
using System;
2012-04-25 22:02:53 +02:00
using System.Windows;
using System.Windows.Media;
namespace MapControl
{
2012-05-04 12:52:20 +02:00
/// <summary>
/// Contains helper methods for creating GlyphRun objects.
/// </summary>
2012-04-25 22:02:53 +02:00
public static class GlyphRunText
{
public static GlyphRun Create(string text, Typeface typeface, double emSize, Point baselineOrigin = new Point())
2012-04-25 22:02:53 +02:00
{
GlyphTypeface glyphTypeface;
if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
{
throw new ArgumentException(string.Format("{0}: No GlyphTypeface found", typeface.FontFamily));
2012-04-25 22:02:53 +02:00
}
var glyphIndices = new ushort[text.Length];
var advanceWidths = new double[text.Length];
2012-04-25 22:02:53 +02:00
for (int i = 0; i < text.Length; i++)
{
var glyphIndex = glyphTypeface.CharacterToGlyphMap[text[i]];
2012-04-25 22:02:53 +02:00
glyphIndices[i] = glyphIndex;
advanceWidths[i] = glyphTypeface.AdvanceWidths[glyphIndex] * emSize;
}
return new GlyphRun(glyphTypeface, 0, false, emSize, glyphIndices, baselineOrigin, advanceWidths, null, null, null, null, null, null);
2012-04-25 22:02:53 +02:00
}
public static void DrawGlyphRun(this DrawingContext drawingContext, Brush foreground, GlyphRun glyphRun,
Point position, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment)
2012-04-25 22:02:53 +02:00
{
var boundingBox = glyphRun.ComputeInkBoundingBox();
2012-04-25 22:02:53 +02:00
switch (horizontalAlignment)
2012-04-25 22:02:53 +02:00
{
case HorizontalAlignment.Center:
position.X -= boundingBox.Width / 2d;
break;
case HorizontalAlignment.Right:
position.X -= boundingBox.Width;
break;
default:
break;
2012-04-25 22:02:53 +02:00
}
switch (verticalAlignment)
2012-04-25 22:02:53 +02:00
{
case VerticalAlignment.Center:
position.Y -= boundingBox.Height / 2d;
break;
case VerticalAlignment.Bottom:
position.Y -= boundingBox.Height;
break;
default:
break;
2012-04-25 22:02:53 +02:00
}
drawingContext.PushTransform(new TranslateTransform(position.X - boundingBox.X, position.Y - boundingBox.Y));
drawingContext.DrawGlyphRun(foreground, glyphRun);
drawingContext.Pop();
2012-04-25 22:02:53 +02:00
}
}
}