using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace Tango.Graphics2D.VisualBinders
{
public class TextBlockBinder : IVisualBinder
{
public void DrawVisual(FrameworkElement element, Drawing2DHost host, DrawingContext context)
{
TextBlock textBlock = element as TextBlock;
double width = 0;
double height = 0;
List<Tuple<FormattedText, double>> runs = new List<Tuple<FormattedText, double>>();
foreach (var run in textBlock.Inlines.OfType<Run>())
{
var typeface = new Typeface(
run.FontFamily,
run.FontStyle,
run.FontWeight,
run.FontStretch);
var formattedText = new FormattedText(run.Text,
CultureInfo.GetCultureInfo("en-us"),
run.FlowDirection,
typeface,
run.FontSize,
run.Foreground);
formattedText.MaxTextWidth = host.ActualWidth;
double w = formattedText.WidthIncludingTrailingWhitespace;
runs.Add(new Tuple<FormattedText, double>(formattedText, w));
width += w;
height = Math.Max(formattedText.Height, height);
}
textBlock.Width = width;
textBlock.Height = height;
var location = host.GetElementLocation(textBlock);
double position_x = location.X;
foreach (var run in runs)
{
context.DrawText(run.Item1, new Point(position_x, location.Y));
position_x += run.Item2;
}
}
public List<DependencyProperty> GetRenderProperties()
{
return new List<DependencyProperty>()
{
TextBlock.OpacityProperty,
TextBlock.VisibilityProperty,
TextBlock.ForegroundProperty,
TextBlock.TextProperty,
TextBlock.FontSizeProperty,
TextBlock.FontFamilyProperty,
TextBlock.FontWeightProperty,
};
}
}
}