This repository has been archived by the owner on Dec 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ColorFormatter.cs
74 lines (64 loc) · 1.97 KB
/
ColorFormatter.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows.Media;
namespace GTAVNativesWrapper
{
/// <summary>
/// That class allows us to use GTA formatting codes like ~r~Red text
/// </summary>
public static class ColorFormatter
{
private static Dictionary<char, Color> colors = new Dictionary<char, Color>();
/// <summary>
/// Register a color that will be used in <see cref="GetFormattedText(string)"/>
/// </summary>
/// <param name="char">The char assigned to the color</param>
/// <param name="color">The color the text will be colored into</param>
public static void RegisterColor(char @char, Color color)
{
colors.Add(@char, color);
}
public static Color GetColor(char @char)
{
return colors.ContainsKey(@char) ? colors[@char] : Colors.Black;
}
/// <summary>
/// Returns a formatted text (a text colored using the known color codes, <see cref="RegisterColor(char, Color)"/>)
/// </summary>
/// <param name="text">The unformatted text</param>
/// <returns>The formatted text</returns>
public static List<Run> GetFormattedText(string text)
{
List<Run> runs = new List<Run>();
char[] chars = text.ToArray();
Color currentColor = Colors.Black;
StringBuilder currentText = new StringBuilder();
for(int i = 0; i < chars.Length; i++)
{
if(i < chars.Length - 3 && chars[i] == '~' && chars[i + 2] == '~' && Char.IsLetterOrDigit(chars[i + 1]))
{
if(currentText.Length != 0)
{
Run run = new Run(currentText.ToString());
run.Foreground = new SolidColorBrush(currentColor);
runs.Add(run);
currentText = new StringBuilder();
}
currentColor = GetColor(chars[i+1]);
i+=2;
}
else currentText.Append(chars[i]);
}
if(currentText.Length != 0)
{
Run run = new Run(currentText.ToString());
run.Foreground = new SolidColorBrush(currentColor);
runs.Add(run);
}
return runs;
}
}
}