public static void ApplyText(UICheckboxDropDown dd, string text) { UIButton uibutton = (UIButton)dd.triggerButton; var padding = uibutton.textPadding; padding.left = 5; padding.right = 21; uibutton.text = text; // must set text to mearure text once and only once. using (UIFontRenderer uifontRenderer = ObtainTextRenderer(uibutton)) { float p2uRatio = uibutton.GetUIView().PixelsToUnits(); var widths = uifontRenderer.GetCharacterWidths(text); float x = widths.Sum() / p2uRatio; //Log.Debug($"{uifontRenderer}.GetCharacterWidths(\"{text}\")->{widths.ToSTR()}"); //if (x > uibutton.width - 42) // uibutton.textHorizontalAlignment = UIHorizontalAlignment.Left; //else // uibutton.textHorizontalAlignment = UIHorizontalAlignment.Center; if (x > uibutton.width - uibutton.textPadding.horizontal) { for (int n = 4; n < text.Length; ++n) { float x2 = widths.Take(n).Sum() / p2uRatio + 15; // 15 = width of ... if (x2 > uibutton.width - 21) { text = text.Substring(0, n - 1) + "..."; break; } } } } uibutton.text = text; }
public static bool Truncate(UILabel label, string text, string suffix = "…") { bool flag = false; try { using (UIFontRenderer renderer = label.ObtainRenderer()) { float units = label.GetUIView().PixelsToUnits(); float[] characterWidths = renderer.GetCharacterWidths(text); float num1 = 0.0f; float num2 = (float)((double)label.width - (double)label.padding.horizontal - 2.0); for (int index = 0; index < characterWidths.Length; ++index) { num1 += characterWidths[index] / units; if ((double)num1 > (double)num2) { flag = true; text = text.Substring(0, index - 3) + suffix; break; } } } label.text = text; } catch { flag = false; } return(flag); }
public static void FitString(this UILabel label) { using (UIFontRenderer fontRenderer = label.ObtainRenderer()) { float p2u = label.GetUIView().PixelsToUnits(); var characterWidths = fontRenderer.GetCharacterWidths(label.text); float totalSize = label.padding.left + label.padding.right; for (var i = 0; i < characterWidths.Length; i++) { totalSize += characterWidths[i] / p2u; if (!(totalSize > label.width)) { continue; } label.tooltip = label.text; label.text = string.Concat(label.text.Substring(0, i - 1), "..."); break; } } }