1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Xamarin.Forms
{
public sealed class FontTypeConverter : TypeConverter
{
public override object ConvertFromInvariantString(string value)
{
// string should be formatted as "[name],[attributes],[size]" there may be multiple attributes, e.g. "Georgia, Bold, Italic, 42"
if (value != null)
{
// trim because mono implements Enum.Parse incorrectly and fails to trim correctly.
List<string> parts = value.Split(',').Select(s => s.Trim()).ToList();
string name = null;
var bold = false;
var italic = false;
double size = -1;
NamedSize namedSize = 0;
// check if last is a size
string last = parts.Last();
double trySize;
NamedSize tryNamedSize;
if (double.TryParse(last, NumberStyles.Number, CultureInfo.InvariantCulture, out trySize))
{
size = trySize;
parts.RemoveAt(parts.Count - 1);
}
else if (Enum.TryParse(last, out tryNamedSize))
{
namedSize = tryNamedSize;
parts.RemoveAt(parts.Count - 1);
}
// check if first is a name
foreach (string part in parts)
{
FontAttributes tryAttibute;
if (Enum.TryParse(part, out tryAttibute))
{
// they did not provide a font name
if (tryAttibute == FontAttributes.Bold)
bold = true;
else if (tryAttibute == FontAttributes.Italic)
italic = true;
}
else
{
// they may have provided a font name
if (name != null)
throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", value, typeof(Font)));
name = part;
}
}
FontAttributes attributes = 0;
if (bold)
attributes = attributes | FontAttributes.Bold;
if (italic)
attributes = attributes | FontAttributes.Italic;
if (size == -1 && namedSize == 0)
namedSize = NamedSize.Medium;
if (name != null)
{
if (size == -1)
{
return Font.OfSize(name, namedSize).WithAttributes(attributes);
}
return Font.OfSize(name, size).WithAttributes(attributes);
}
if (size == -1)
{
return Font.SystemFontOfSize(namedSize, attributes);
}
return Font.SystemFontOfSize(size, attributes);
}
throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", value, typeof(Font)));
}
}
}
|