Xamarin.iOS和Xamarin.Android中计算文本宽度的方法

Xamarin.iOS

    CoreGraphics.CGSize cGSize = new CoreGraphics.CGSize(1000, 1000);
        public double getDisplayLength(string str) {
            var s = new NSAttributedString(str);
            var size = s.GetBoundingRect(cGSize, NSStringDrawingOptions.UsesLineFragmentOrigin, null);
            return size.Width;
        }

Xamarin.Android

        Paint paint = new Paint();
        public double getDisplayLength(string str) {
            float[] widths = new float[str.Length];
            paint.GetTextWidths(str, widths);
            float sum = 0;
            widths.ForEachWithIndex((o, index) => {
                sum += o;
            });

            return sum;
        }

其中ForEachWithIndex是我自己写的一个扩展方法,方便遍历数组;

public static void ForEachWithIndex<T>(this T[] array, Action<T, int> action) {
            for (int i = 0; i < array.Length; i++) {
                action(array[i], i);
            }
        }

推荐阅读更多精彩内容