Recently, Xamarin.Forms Label has support for FormattedText. So I want to use that FormattedText property to load the markdown text. For example,
I have below kinds of markdown text,
1. **Hi**, How are you?
2. Hello **John**, _Good Morning_
I want to automatically convert the markdown text like above into the FormattedString to set to the Label.FormattedText.
Could anyone help me to achieve this?
Note: I don't want to go for third party MarkdownView controls since they are heavy-weight control and having some issues on rendering the UI when I checked on Xamarin.Forms iOS.
Finally, I wrote my own parsing and converted the markdown text into the FormattedString.
public static FormattedString GetFormattedString(this string text, double defaultFontSize)
{
var boldFormat = "**";
var italicFormat = "_";
var formatString = new FormattedString();
var temp = text;
while(!string.IsNullOrWhiteSpace(temp))
{
try
{
var boldIndex = temp.IndexOf(boldFormat);
var italicIndex = temp.IndexOf(italicFormat);
if (italicIndex >= 0 && (italicIndex < boldIndex || boldIndex < 0))
{
if (italicIndex > 0)
{
var t = temp.Substring(0, italicIndex);
formatString.Spans.Add(new Span() { Text = t });
}
temp = temp.Substring(italicIndex + 1);
var next = temp.IndexOf(italicFormat);
var t1 = temp.Substring(0, next);
formatString.Spans.Add(new Span() { Text = t1, FontAttributes = FontAttributes.Italic, FontSize = defaultFontSize });
temp = temp.Substring(next + 1);
}
else if (boldIndex >= 0)
{
if (boldIndex > 0)
{
var t = temp.Substring(0, boldIndex);
formatString.Spans.Add(new Span() { Text = t });
}
temp = temp.Substring(boldIndex + 2);
var next = temp.IndexOf(boldFormat);
var t1 = temp.Substring(0, next);
formatString.Spans.Add(new Span() { Text = t1, FontAttributes = FontAttributes.Bold, FontSize = defaultFontSize });
temp = temp.Substring(next + 2);
}
else
{
formatString.Spans.Add(new Span() { Text = temp, FontSize = defaultFontSize });
break;
}
}
catch (Exception)
{
formatString = new FormattedString();
formatString.Spans.Add(new Span() { Text = text, FontSize = defaultFontSize });
break;
}
}
return formatString;
}
Note: Currently, I have added code bold and italic formats only. Need to extend it for the required markdown formats.