Skip to content

Commit

Permalink
allow to change monospacefont
Browse files Browse the repository at this point in the history
  • Loading branch information
whistyun committed Dec 26, 2020
1 parent 78f5ef9 commit 7ce1fc6
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 31 deletions.
44 changes: 13 additions & 31 deletions ColorTextBlock.Avalonia/CCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,47 +2,29 @@
using System.Collections.Generic;
using System.Linq;
using Avalonia.Media;
using Avalonia;
using ColorTextBlock.Avalonia.Fonts;

namespace ColorTextBlock.Avalonia
{
public class CCode : CSpan
{
private readonly static FontFamily Monospace;
public static readonly StyledProperty<FontFamily> MonospaceFontFamilyProperty =
AvaloniaProperty.Register<CCode, FontFamily>(
nameof(MonospaceFontFamily),
defaultValue: FontFamilyCollecter.TryGetMonospace() ?? FontFamily.Default,
inherits: true);

static CCode()
public CCode(IEnumerable<CInline> inlines) : base(inlines)
{
string[] RequestFamilies = {
"menlo",
"monaco",
"consolas",
"droid sans mono",
"inconsolata",
"courier new",
"monospace",
"droid sans fallback"
};

var monospaceName = FontManager.Current.GetInstalledFontFamilyNames()
.Where(name => RequestFamilies.Any(reqNm => name.ToLower().Contains(reqNm)))
.FirstOrDefault();

if (String.IsNullOrEmpty(monospaceName))
{
// giveup
Monospace = null;
}
else
{
Monospace = new FontFamily(monospaceName);
}
var obsvr = this.GetBindingObservable(MonospaceFontFamilyProperty);
Bind(FontFamilyProperty, obsvr);
}

public CCode(IEnumerable<CInline> inlines) : base(inlines)
public FontFamily MonospaceFontFamily
{
if (Monospace != null)
{
FontFamily = Monospace;
}
get { return GetValue(MonospaceFontFamilyProperty); }
set { SetValue(MonospaceFontFamilyProperty, value); }
}
}
}
33 changes: 33 additions & 0 deletions ColorTextBlock.Avalonia/Fonts/FontFamilyCollecter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Avalonia.Media;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ColorTextBlock.Avalonia.Fonts
{
internal class FontFamilyCollecter
{
public static FontFamily TryGetMonospace()
{
string[] RequestFamilies = {
"menlo",
"monaco",
"consolas",
"droid sans mono",
"inconsolata",
"courier new",
"monospace",
"droid sans fallback"
};

var monospaceName = FontManager.Current.GetInstalledFontFamilyNames()
.Where(name => RequestFamilies.Any(reqNm => name.ToLower().Contains(reqNm)))
.FirstOrDefault();

return String.IsNullOrEmpty(monospaceName) ?
null :
new FontFamily(monospaceName);
}
}
}

0 comments on commit 7ce1fc6

Please sign in to comment.