I have created a custom LabelRenderer in my Android app to apply a custom font in a Xamarin Android app (https://developer.xamarin.com/guides/xamarin-forms/user-interface/text/fonts/).
Everything works great for a normal label with the content added to the .Text property. However, if I create a label using .FormattedText property, the custom font is not applied.
Anyone have success doing this? An option, since I'm just stacking lines of different sized text, is to use separate label controls for each, but I'd prefer to use a formatted string if possible.
Here's the guts of my custom renderer:
[assembly: ExportRenderer (typeof (gbrLabel), typeof (gbrLabelRenderer))]
public class gbrLabelRenderer: LabelRenderer
{
protected override void OnElementChanged (ElementChangedEventArgs<Label> e)
{
base.OnElementChanged (e);
var label = (TextView)Control;
Typeface font = Typeface.CreateFromAsset (Forms.Context.Assets, "Lobster-Regular.ttf");
label.Typeface = font;
}
}
And here's my simple label control... all it does is apply the font to iOS, and leaves applying the font for Android up to the custom renderer.
public class gbrLabel: Label
{
public gbrLabel ()
{
Device.OnPlatform (
iOS: () => {
FontFamily = "Lobster-Regular";
FontSize = Device.GetNamedSize(NamedSize.Medium,this);
}
}
}
Works fine for labels with just the .Text property... but not for labels with the .FormattedText property.
Should I keep digging, or just stack my labels since that's an option in this case?
Here's an example of the various ways I've tried this in the Formatted text, since that was requested:
var fs = new FormattedString ();
fs.Spans.Add (new Span {
Text = string.Format("LINE 1\n",Title),
FontSize = Device.GetNamedSize(NamedSize.Large,typeof(Label))
});
fs.Spans.Add (new Span {
Text = string.Format ("LINE 2\n"),
FontSize = Device.GetNamedSize(NamedSize.Large,typeof(Label)) * 2,
FontAttributes = FontAttributes.Bold,
FontFamily = "Lobster-Regular"
});
fs.Spans.Add (new Span {
Text = string.Format ("LINE 3\n"),
FontSize = Device.GetNamedSize(NamedSize.Medium,typeof(Label)),
FontFamily = "Lobster-Regular.ttf"
});
gbrLabel lblContent = new gbrLabel {
FormattedText = fs
}
None of these (the first should be set by the default class / renderer, and the second 2 are variations of including the font in a span definition itself) work on Android.
Note: Android and iOS issues have been summarized on a blog post: smstuebe.de/2016/04/03/formattedtext.xamrin.forms/
The font is set as long as you do not set FontSize or FontAttributes. So I had the look at the implementation and found that the FormattedText is trying to load the font like the default renderer which doesn't work on Android.
The android formatting system works very similar to that one of Xamarin.Forms. It's using spans to define text attributes. The renderer is adding a FontSpan for every Span with a custom font, size or attribute. Unfortunately, the FontSpanclass is a private inner class of FormattedStringExtensions so we have to deal with reflections.
Our Renderer is updating the Control.TextFormatted on initialization and when the FormattedText property changes. In the update method, we get all FontSpans and replace them with our CustomTypefaceSpan.
Renderer
public class FormattedLabelRenderer : LabelRenderer
{
private static readonly Typeface Font = Typeface.CreateFromAsset(Forms.Context.Assets, "LobsterTwo-Regular.ttf");
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
Control.Typeface = Font;
UpdateFormattedText();
}
private void UpdateFormattedText()
{
if (Element.FormattedText != null)
{
var extensionType = typeof(FormattedStringExtensions);
var type = extensionType.GetNestedType("FontSpan", BindingFlags.NonPublic);
var ss = new SpannableString(Control.TextFormatted);
var spans = ss.GetSpans(0, ss.ToString().Length, Class.FromType(type));
foreach (var span in spans)
{
var start = ss.GetSpanStart(span);
var end = ss.GetSpanEnd(span);
var flags = ss.GetSpanFlags(span);
var font = (Font)type.GetProperty("Font").GetValue(span, null);
ss.RemoveSpan(span);
var newSpan = new CustomTypefaceSpan(Control, font);
ss.SetSpan(newSpan, start, end, flags);
}
Control.TextFormatted = ss;
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Label.FormattedTextProperty.PropertyName)
{
UpdateFormattedText();
}
}
}
I'm not sure, why you introduced a new element type gbrLabel, but as long as you only wan't to change the renderer, you don't have to create a custom element. You can replace the renderer of the default element:
[assembly: ExportRenderer(typeof(Label), typeof(FormattedLabelRenderer))]
CustomTypefaceSpan
public class CustomTypefaceSpan : MetricAffectingSpan
{
private readonly Typeface _typeFace;
private readonly Typeface _typeFaceBold;
private readonly Typeface _typeFaceItalic;
private readonly Typeface _typeFaceBoldItalic;
private readonly TextView _textView;
private Font _font;
public CustomTypefaceSpan(TextView textView, Font font)
{
_textView = textView;
_font = font;
// Note: we are ignoring _font.FontFamily (but thats easy to change)
_typeFace = Typeface.CreateFromAsset(Forms.Context.Assets, "LobsterTwo-Regular.ttf");
_typeFaceBold = Typeface.CreateFromAsset(Forms.Context.Assets, "LobsterTwo-Bold.ttf");
_typeFaceItalic = Typeface.CreateFromAsset(Forms.Context.Assets, "LobsterTwo-Italic.ttf");
_typeFaceBoldItalic = Typeface.CreateFromAsset(Forms.Context.Assets, "LobsterTwo-BoldItalic.ttf");
}
public override void UpdateDrawState(TextPaint paint)
{
ApplyCustomTypeFace(paint);
}
public override void UpdateMeasureState(TextPaint paint)
{
ApplyCustomTypeFace(paint);
}
private void ApplyCustomTypeFace(Paint paint)
{
var tf = _typeFace;
if (_font.FontAttributes.HasFlag(FontAttributes.Bold) && _font.FontAttributes.HasFlag(FontAttributes.Italic))
{
tf = _typeFaceBoldItalic;
}
else if (_font.FontAttributes.HasFlag(FontAttributes.Bold))
{
tf = _typeFaceBold;
}
else if (_font.FontAttributes.HasFlag(FontAttributes.Italic))
{
tf = _typeFaceItalic;
}
paint.SetTypeface(tf);
paint.TextSize = TypedValue.ApplyDimension(ComplexUnitType.Sp, _font.ToScaledPixel(), _textView.Resources.DisplayMetrics);
}
}
Our Custom CustomTypefaceSpanis similar to the FontSpan of Xamarin.Forms, but is loading the custom fonts and can load different fonts for different FontAttributes.
The result is a nice colorful Text :)
Related
i need to measure the string width and height depending on some style attributes like font, fontsize and fontattributes (bold/italic). How can i do this?
Thank you!
In Android, it provide the getTextBounds to retrieve the text boundary box and store to bounds. Return in bounds.
https://developer.android.com/reference/android/graphics/Paint#getTextBounds(java.lang.CharSequence,%20int,%20int,%20android.graphics.Rect)
In Xamarin.Forms, we could use Dependency Service to do that.
public interface CalculateTextWidth
{
double calculateWidth(string text);
}
Android Implementation:
[assembly: Dependency(typeof(CalculateTextWidth_Android))]
namespace App6.Droid
{
public class CalculateTextWidth_Android : CalculateTextWidth
{
public double calculateWidth(string text)
{
Rect bounds = new Rect();
TextView textView = new TextView(Forms.Context);
textView.Paint.GetTextBounds(text, 0, text.Length, bounds);
var length = bounds.Width();
return length / Resources.System.DisplayMetrics.ScaledDensity;
}
}
}
Usage:
private void Button_Clicked(object sender, EventArgs e)
{
var s = DependencyService.Get<CalculateTextWidth>().calculateWidth(label.Text);
}
I now use SkiaSharps MeasureText Method.
Using Xamarin Forms (version 2.5.0.121934), I'm working on an app targeting Android, iOS, and UWP. I need to add underlining and strikethrough to some text, which require custom renderers. For Android and iOS, everything is working fine, and on UWP, applying strikethrough or underline works correctly, but removing those decorations isn't working.
Here's the entirety of the UWP renderer:
[assembly: ExportRenderer(typeof(EnhancedLabel), typeof(EnhancedLabelRenderer))]
namespace myApp.UWP
{
public class EnhancedLabelRenderer : LabelRenderer
{
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var strikethrough = ((EnhancedLabel)sender).Strikethrough;
var underline = ((EnhancedLabel)sender).Underline;
if (strikethrough && underline)
{
Control.TextDecorations = TextDecorations.Strikethrough | TextDecorations.Underline;
}
else if (strikethrough)
{
Control.TextDecorations = TextDecorations.Strikethrough;
}
else if (underline)
{
Control.TextDecorations = TextDecorations.Underline;
}
else
{
Control.TextDecorations = TextDecorations.None;
}
}
}
}
EnhancedLabel is a simple class that extends Xamarin.Forms.Label and adds the simple BindableProperty fields that specify strikethrough or underlining.
The renderer is properly setting TextDecorations.None, but that isn't having an effect on the UI. I've worked through this in the debugger, and can actually see that the state of the TextBlock within the ExtendedLabel has TextDecorations.None, but the UI is still drawing it with underlining or strikethrough (essentially, either of those can be added, but neither can be removed).
I've gone through the Xamarin documentation and looked at the bugs in Bugzilla, and haven't found any clues. Has any one else encountered this? Wondering if there's a UWP-specific call I need to make that I missed, or if using TextDecorations is the wrong way to apply the styles, or if I've actually stumbled across a bug.
Bug in UWP as in Xaml below:
<TextBlock>
<Run Text="Decorations can be toggled on and off"/>
</TextBlock>
<TextBlock Text="Decorations will not toggle off"/>
It is the same issue if you code the TextBlock:
TextBlock textBlock = new TextBlock { FontSize = 18.0 };
textBlock.Inlines.Add(new Windows.UI.Xaml.Documents.Run { Text = "This text will not stick on text decoration." });
TextBlock textBlockBad = new TextBlock
{
FontSize = 18.0,
Text = "This text will not enable the TextDecorations to be turned off"
};
Same behaviour found with Typography.Capitals
Just need to use only Inlines for TextBlocks and presumably RichTextBlocks to avoid these issues.
Wondering if there's a UWP-specific call I need to make that I missed, or if using TextDecorations is the wrong way to apply the styles, or if I've actually stumbled across a bug.
If you want yo use TextDecorations, you could use the Run instance to pack the decorated text like the follow.
Underline ul = new Underline();
ul.TextDecorations = TextDecorations.Strikethrough;
Run r = new Run();
r.Text = "Here is an underlined text";
ul.Inlines.Add(r);
MyTextBlock.Inlines.Add(ul);
For you requirement, I have create a CustomLabel that you could use directly.
CustomLabel.cs
public class CustomLabel : Label
{
public static readonly BindableProperty DeckProperty = BindableProperty.Create(
propertyName: "Deck",
returnType: typeof(TextDeck),
declaringType: typeof(CustomLabel),
defaultValue: default(TextDeck));
public TextDeck Deck
{
get { return (TextDeck) GetValue(DeckProperty); }
set { SetValue(DeckProperty, value); }
}
}
public enum TextDeck
{
None = 0,
//
// Summary:
// Underline is applied to the text.
Underline = 1,
//
// Summary:
// Strikethrough is applied to the text.
Strikethrough = 2
}
CustomLabelRenderer.cs
public class CustomLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (Control != null)
{
var element = Element as CustomLabel;
var underline = new Underline();
var run = new Run();
switch (element.Deck)
{
case TextDeck.None:
underline.TextDecorations = TextDecorations.None;
break;
case TextDeck.Strikethrough:
underline.TextDecorations = TextDecorations.Strikethrough;
break;
case TextDeck.Underline:
underline.TextDecorations = TextDecorations.Underline;
break;
}
run.Text = element.Text;
underline.Inlines.Add(run);
Control.Inlines.Clear();
Control.Inlines.Add(underline);
}
}
}
Usage
<local:CustomLabel Deck="Underline" Text="Welcome to Xamarin.Forms!" />
I saw this example:
Xamarin Forms - How to create custom render to give TableSection the default iOS Footer?
It does 75% of what I am looking for with this code:
using CoreGraphics;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(TableView), typeof(Japanese.iOS.TableViewCustomRenderer))]
namespace Japanese.iOS
{
public class TableViewCustomRenderer : TableViewRenderer
{
UITableView tableView;
protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
{
base.OnElementChanged(e);
if (Control == null)
return;
var tableView = Control as UITableView;
var formsTableView = Element as TableView;
tableView.WeakDelegate = new CustomFooterTableViewModelRenderer(formsTableView);
}
void Current_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
}
private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
{
public CustomFooterTableViewModelRenderer(TableView model) : base(model)
{
}
public override nfloat GetHeightForFooter(UITableView tableView, nint section)
{
return 10;
}
public override string TitleForFooter(UITableView tableView, nint section)
{
return "This is the title for this given section";
}
}
}
}
1. However what I would like is to be able to extend TableView so that I am able to put in the XAML some way to set or leave unset the footer text and height. Something like:
<ExtTableView FooterText="abc" FooterHeight="50". ..
2. From experiments with the code above I tried hardcoding in some text and realize that there is no spacing set. So I would also like to find out if there is a way to set the spacing and font so it appears just like in the iOS settings pages?
Could someone suggest how I could go about creating what I am looking for which is I guess something like an ExtTableView class that can accept additional arguments.
As hankide said , I just provide more details.
However what I would like is to be able to extend TableView so that I am able to put in the XAML some way to set or leave unset the footer text and height.
Create MyTableView that inherits from TableView
public class MyTableView : TableView
{
public static readonly BindableProperty FooterHeightProperty =
BindableProperty.Create("FooterHeight", typeof(string), typeof(MyTableView), "");
public string FooterHeight
{
get { return (string)GetValue(FooterHeightProperty); }
set { SetValue(FooterHeightProperty, value); }
}
public static readonly BindableProperty FooterTextProperty =
BindableProperty.Create("FooterText", typeof(string), typeof(MyTableView), "");
public string FooterText
{
get { return (string)GetValue(FooterTextProperty); }
set { SetValue(FooterTextProperty, value); }
}
}
Get the value that you set in XMAL and assign them to CustomFooterTableViewModelRenderer
protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
{
base.OnElementChanged(e);
if (Control == null)
return;
var tableView = Control as UITableView;
var formsTableView = Element as MyTableView;
CustomFooterTableViewModelRenderer render = new CustomFooterTableViewModelRenderer(formsTableView);
render.height = float.Parse(formsTableView.FooterHeight);
render.text = formsTableView.FooterText;
tableView.WeakDelegate = render;
}
private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
{
public float height { get; set; }
public String text { get; set; }
public CustomFooterTableViewModelRenderer(TableView model) : base(model)
{
}
public override UIView GetViewForFooter(UITableView tableView, nint section)
{
UIView view = new UIView(new CGRect(0, 0, tableView.Frame.Width, 50));
view.BackgroundColor = UIColor.Gray;
UILabel label = new UILabel();
label.Frame = new CGRect(0, 0, tableView.Frame.Width, height);
label.BackgroundColor = UIColor.Red;
label.Text = text;
label.Font = UIFont.SystemFontOfSize(15);
view.Add(label);
return view;
}
public override nfloat GetHeightForFooter(UITableView tableView, nint section)
{
return 50;
}
}
Usage:
<local:MyTableView FooterHeight="20" FooterText="ABC">
<TableRoot>
<TableSection>
<TextCell Text="22222" ></TextCell>
</TableSection>
</TableRoot>
</local:MyTableView>
From experiments with the code above I tried hardcoding in some text and realize that there is no spacing set. So I would also like to find out if there is a way to set the spacing and font so it appears just like in the iOS settings pages?
You could override the method GetViewForFooter to change the defalut style of footer,find it in the code above .
My test :
You had the right idea about creating the custom control. Here's what to do:
Create ExtTableView class that inherits from TableView
public class ExtTableView : TableView { }
Create BindableProperties for both FooterText and FooterHeight, as outlined here.
After that you can set the properties in XAML
<ExtTableView FooterText="abc" FooterHeight="50" ...
Within the renderer, you can get the values from Element (which points to our Xamarin.Forms ExtTableView).
// Modify the native control with these values
var text = Element.FooterText;
var height = Element.FooterHeight;
How to set Placeholder Text and Placeholder Color in Editor in Xamarin Forms.
It has no default Functionality or Properties how to customize it?
Reference documentation : Xamarin Forms Editor
You will need a custom renderer for that (Here is the Android Custom Renderer) you will need another renderer for iOS:
public class PlaceholderEditor : Editor
{
public static readonly BindableProperty PlaceholderProperty =
BindableProperty.Create<PlaceholderEditor, string>(view => view.Placeholder, String.Empty);
public PlaceholderEditor()
{
}
public string Placeholder
{
get
{
return (string)GetValue(PlaceholderProperty);
}
set
{
SetValue(PlaceholderProperty, value);
}
}
}
public class PlaceholderEditorRenderer : EditorRenderer
{
public PlaceholderEditorRenderer()
{
}
protected override void OnElementChanged(
ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var element = e.NewElement as PlaceholderEditor;
this.Control.Hint = element.Placeholder;
}
}
protected override void OnElementPropertyChanged(
object sender,
PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == PlaceholderEditor.PlaceholderProperty.PropertyName)
{
var element = this.Element as PlaceholderEditor;
this.Control.Hint = element.Placeholder;
}
}
}
And for the color you may need something like this (Android):
Control.SetHintTextColor(Android.Graphics.Color.White);
There already a thread for this in the Xamarin Forums:
https://forums.xamarin.com/discussion/20616/placeholder-editor
And more about Custom Renderers information below:
https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/
Set the placeholder string to your Editor's Text in Xaml
Then in Code behind file:
InitializeComponent();
var placeholder = myEditor.Text;
myEditor.Focused += (sender, e) =>
{
// Set the editor's text empty on focus, only if the place
// holder is present
if (myEditor.Text.Equals(placeholder))
{
myEditor.Text = string.Empty;
// Here You can change the text color of editor as well
// to active text color
}
};
myEditor.Unfocused += (sender, e) =>
{
// Set the editor's text to place holder on unfocus, only if
// there is no data entered in editor
if (string.IsNullOrEmpty(myEditor.Text.Trim()))
{
myEditor.Text = placeholder;
// Here You can change the text color of editor as well
// to dim text color (Text Hint Color)
}
};
In my application I have a Contentpage with a Scrollview in it. The Scrollview in turn contains a StackLayout with lots of labels with text. In the middle of this I want to insert some static HTML.
I have tried adding a Webview with static HTML as a child to the StackLayout but the Webview is not visible then (Probably the height gets calculated to zero)
Does anyone know how to fix this? Or is there some other way to add HTML in the between all the labels?
StackLayout mainLayout = new StackLayout ();
// Adding many labels of different sizes
mainLayout.Children.Add (new Label {Text = "Label text"});
mainLayout.Children.Add ( new WebView {
Source = new HtmlWebViewSource {
Html = "<html><body>Hello</body></html>"
}
});
// Adding many more labels of different sizes
mainLayout.Children.Add (new Label {Text = "Even more Label text"});
Content = new ScrollView {
Content = mainLayout
};
See https://developer.xamarin.com/guides/xamarin-forms/user-interface/webview/, in particular:
WebView requires that HeightRequest and WidthRequest are specified
when contained in StackLayout or RelativeLayout. If you fail to
specify those properties, the WebView will not render.
The HeightRequest and WidthRequest are not set in the code snippet above, so fixing this should be the next thing to try.
I found a great solution here
using Xamarin.Forms;
namespace YourNamespace
{
public class HtmlLabel : Label
{
}
}
iOS renderer
[assembly: ExportRenderer(typeof(HtmlLabel), typeof(HtmlLabelRenderer))]
namespace YourNamespace
{
class HtmlLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (e.NewElement == null)
{
return;
}
var attr = new NSAttributedStringDocumentAttributes();
var nsError = new NSError();
attr.DocumentType = NSDocumentType.HTML;
var text = e.NewElement.Text;
//I wrap the text here with the default font and size
text = "<style>body{font-family: '" + this.Control.Font.Name + "'; font-size:" + this.Control.Font.PointSize + "px;}</style>" + text;
var myHtmlData = NSData.FromString(text, NSStringEncoding.Unicode);
this.Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (this.Control == null)
{
return;
}
if (e.PropertyName == Label.TextProperty.PropertyName)
{
var attr = new NSAttributedStringDocumentAttributes();
var nsError = new NSError();
attr.DocumentType = NSDocumentType.HTML;
var myHtmlData = NSData.FromString(this.Control.Text, NSStringEncoding.Unicode);
this.Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
}
}
}
}
Android renderer
[assembly: ExportRenderer(typeof(HtmlLabel), typeof(HtmlLabelRenderer))]
namespace YourNamespace
{
class HtmlLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
Control?.SetText(Html.FromHtml(Element.Text), TextView.BufferType.Spannable);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Label.TextProperty.PropertyName)
{
Control?.SetText(Html.FromHtml(Element.Text), TextView.BufferType.Spannable);
}
}
}
}
I found Html.FromHtmlis pretty basic. I ended up binding this library which helped with lists and (with a bit of work) span tags.