You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Forms iOS中使用UIStringAttributes时如何获取UITextView行高?

自定义UIStringAttributes.Font后行高计算不准确的问题

我在设置UIStringAttributes.Font时遇到行高计算错误的问题:

  • 不设置该属性时,系统默认使用Helvetica 12pt字体,计算出的行高13.8是准确的;
  • 手动设置为Arial 17pt字体后,计算得到的18.99行高与实际显示不符。

相关代码

void SetAttributes(string text)
{
  NSMutableAttributedString astr = new NSMutableAttributedString();
  UIStringAttributes attrs;
  NSAttributedString str;
  CheckBox cb;
  string[] lines;
  string line;

  lines = text.Split("\n", StringSplitOptions.None);
  for (int i = 0; i < lines.Count(); i++)
  {
            cb = _checks[i];
            line = lines[i];

    if (i + 1 < _checks.Count)
      line += "\n";

    attrs = new UIStringAttributes();
    attrs.ForegroundColor = cb.Color;

    ////////////////////////////////
    //注释掉这一行后,Draw方法中的行高计算是准确的
    attrs.Font = Control.Font;
    ////////////////////////////////

    str = new NSAttributedString(line, attrs);

    astr.Append(str);
        }

  Control.AttributedText = astr;
}

public override void Draw(CGRect rect)
{
  double baseline = editor.Padding.Top + Control.Font.Ascender;
  double movingBaseline = baseline + BOTTOM_MARGIN;
  double scrollY = Control.ContentOffset.Y;

  double _lineHeight = Control.Font.LineHeight;

  //获取图形上下文
  using (CGContext g = UIGraphics.GetCurrentContext())
  {
    for (int i = 0; i < _lines.Count; i++)
    {
        CGPath path = new CGPath();

      //设置绘图属性
      g.SetLineWidth(0.5f);
      UIColor.Black.SetStroke();

      //添加线条路径
      path.AddLines(new CGPoint[] { 
          new CGPoint(0, movingBaseline - scrollY),
          new CGPoint(300, movingBaseline - scrollY) 
      });

      //添加路径到上下文并绘制
      g.AddPath(path);
      g.DrawPath(CGPathDrawingMode.Stroke);

      //绑定到控件基线以避免累计舍入误差
      movingBaseline = baseline + BOTTOM_MARGIN + (_lineHeight * (double)(i + 1));
    }
  }

  base.Draw(rect);
}

已尝试的无效方案

  • 更换为Consolas字体,行高计算依然错误;
  • 调用NSString(text).StringSize获取高度,得到的19也与实际不符;
  • 尝试通过UIStringAttributes.ParagraphStyle.LineHeight设置行高,但Xamarin未实现该属性的setter,无法配置。

求可行的解决思路?

内容的提问来源于stack exchange,提问作者jho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 08:45:38