Created
May 17, 2021 14:18
-
-
Save HeikkiDev/9ccd7089f809a20e73e12e36cd8f60e8 to your computer and use it in GitHub Desktop.
Measure Label width on platform (Android and iOS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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