Skip to content

Instantly share code, notes, and snippets.

@HeikkiDev
Created May 17, 2021 14:18
Show Gist options
  • Select an option

  • Save HeikkiDev/9ccd7089f809a20e73e12e36cd8f60e8 to your computer and use it in GitHub Desktop.

Select an option

Save HeikkiDev/9ccd7089f809a20e73e12e36cd8f60e8 to your computer and use it in GitHub Desktop.
Measure Label width on platform (Android and iOS)
// ANDROID
public double GetStringWidthMeasure(string stringToMeasure)
{
using (var bounds = new Android.Graphics.Rect())
{
using (var textView = new TextView(Application.Context))
{
var lineCount = textView.LineCount; // line count, I guess!
textView.Paint?.GetTextBounds(stringToMeasure, 0, stringToMeasure.Length, bounds);
var displayMetrics = new DisplayMetrics();
CrossCurrentActivity.Current.Activity.WindowManager?.DefaultDisplay?.GetMetrics(displayMetrics);
return bounds.Width() / displayMetrics.ScaledDensity;
}
}
}
// iOS
public double GetStringWidthMeasure(string stringToMeasure)
{
using (var uiLabel = new UILabel {Text = stringToMeasure})
{
var lineCount = uiLabel.Lines; // line count, I guess!
CGSize length = uiLabel.Text.StringSize(uiLabel.Font);
return length.Width;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment