1

我认为现在可以在 IOS 应用程序中强制您的数字在使用自定义字体时是等宽的。我找到了示例并使用了一些可以编译的代码,但我的数字间距仍然是成比例的。有没有人得到这个工作,如果是这样,我做错了什么?!

这是我的代码:

UIFont bigNumberFont = UIFont.FromName("Dosis-Light", 60f);

var originalDescriptor = bigNumberFont.FontDescriptor;
var attributes = new UIFontAttributes(new UIFontFeature(CTFontFeatureNumberSpacing.Selector.MonospacedNumbers),
            new UIFontFeature((CTFontFeatureCharacterAlternatives.Selector)0));

var newDesc = originalDescriptor.CreateWithAttributes(attributes);

UIFont bigNumberMono = UIFont.FromDescriptor(newDesc, 60f);

lbCurrentPaceMinute.Font = bigNumberMono;

我的自定义字体渲染得很好,但我无法控制数字间距。任何建议都非常感谢!

4

1 回答 1

2

首先,您的代码没有使字体等宽。

您正在调整字体以在等宽模式下呈现数字。所以你所有的数字都有相同的宽度。

下面是一个有 4 个标签的例子,1 是 Docis Light,2 是 Docis Light 与您的调整,第 3 是相同大小的系统字体,第 4 是您调整的系统字体:

ios中的等宽数字字体调整

如您所见,Docis Light 已经支持开箱即用的等宽数字功能,无需任何调整。

如果您需要使用等宽字体,则必须使用自定义等宽字体(设计为等宽字体),或者您可以使用内置的 iOS 等宽字体,例如 Courier 或 Menlo(请参阅http://iosfonts.com上的所有可用 iOS 字体/ )

这是它们在相同场景下的样子:

courier 和 menlo 等宽 iOS 字体

无论是否调整,它们已经是等宽的,并且它们的数字也是等宽的。

最后,如果您需要等宽数字字体(您的代码是做什么的),您不需要调整字符替代。所以代码是:

public static class UIFontExtensions
{
    public static UIFont MonospacedDigitFont(this UIFont font)
    {
        var originalDescriptor = font.FontDescriptor;
        var monospacedNumbersFeature = new UIFontFeature(CTFontFeatureNumberSpacing.Selector.MonospacedNumbers);
        var attributes = new UIFontAttributes(monospacedNumbersFeature);
        var newDescriptor = originalDescriptor.CreateWithAttributes(attributes);
        return UIFont.FromDescriptor(newDescriptor, font.PointSize);
    }
}

希望这可以帮助!我发现深入研究如何在 iOS 中调整字体很有趣。

于 2016-10-14T05:00:34.267 回答