using System; using Shared; #if __IOS__ using UIKit; using Foundation; #else using Android.Graphics; #endif namespace HDL_ON.UI { /// /// TextButton /// 解决iOS 文本到边框有边距问题 /// 支持根据文本动态计算高度 /// public class TextButton : Button { public TextButton() { #if __IOS__ //重写修改文本到边框的内边距为0 (this.uiView as MyButton).ContentEdgeInsets = new UIEdgeInsets(0, 0, 0, 0); #endif } /// /// 设置需要限制的最大行数 /// 但是超过行数的话会缺少省略号...,暂时无法解决 /// public int MaxLine = 0; /// /// 动态计算高度 /// 赋值文本后和指定宽度后,通过计算真实的需要宽度和指定宽度算出多行需要的真实高度 /// 该方法有误差不能100%准确 /// 最正确方法是根据 单行单个字体的高度加上行距来计算 /// /// public int GetMoreLineNeedHeight() { //计算需要的真实宽度 int needWidth = this.GetTextWidth(); //计算在指定宽度情况下,需要的真实行数 int line = (needWidth / this.Width); //求余 int modValue = (needWidth % this.Width); //余大于0,则多加一行 if (modValue > 0) { line = line + 1; } if (line > 0) { if(MaxLine != 0) { line = Math.Min(line, MaxLine); } return line * this.Height; } else { return this.Height; } } int _lineSpacing; /// /// 设置行间距 /// public int LineSpacing { set { _lineSpacing = value; SetButtonLineSpacing(_lineSpacing); } } #if __IOS__ /// /// 按钮设置行距方法 /// /// void SetButtonLineSpacing(int spacing) { UIStringAttributes stringAttributes = new UIStringAttributes { Font = (this.uiView as MyButton).TitleLabel.Font, ForegroundColor = UIColor.Black, ParagraphStyle = new NSMutableParagraphStyle() { LineSpacing = spacing } }; var AttributedText = new NSMutableAttributedString(Text); AttributedText.AddAttributes(stringAttributes, new NSRange(0, Text.Length)); (this.uiView as MyButton).TitleLabel.AttributedText = AttributedText; } /// /// 显示当前文字需要几行 /// /// public int GetNeedLinesWithWidth() { return (this.GetTextWidth() / this.Width) * this.Height; //return 0; } #else /// /// 按钮设置行距方法 /// /// void SetButtonLineSpacing(int spacing) { (this.AndroidView as Android.Widget.Button).SetLineSpacing(spacing, 1); } /// /// /// /// int GetTextHeight() { string text = "Text"; Rect rect = new Rect(); (this.AndroidView as Android.Widget.Button).Paint.GetTextBounds(text, 0, text.Length, rect); return rect.Height(); } #endif } }