gpt4 book ai didi

ios - 系统字体 "Hiragino Sans"显示为剪裁的上升和下降

转载 作者:行者123 更新时间:2023-12-01 16:02:31 24 4
gpt4 key购买 nike

我需要在我的应用程序中使用 iOS 的系统字体“Hiragino Sans W3”,但无论我选择哪种大小/样式或 UILabel 的尺寸,字体的上升和下降总是出现剪裁:

enter image description here

这似乎可以通过创建 UILabel 的子类并覆盖方法 textRectForBounds:limitedToNumberOfLines: 以返回“正确”值来解决。所以下面的代码...

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect result = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
result = CGRectInset(result, 0, -5);
return result;
}

...导致上升端和下降端不再被剪裁:

enter image description here

我知道也可以使用外部编辑器来调整字体的升序和降序位置。 但这是系统字体,不加任何修改不应该能正常工作吗?我在这里遗漏了什么吗?

提前感谢您的回答。

最佳答案

我认为这个问题实际上归结为字体本身(“Hiragino Sans”)。使用字体编辑器可以看到字形超出了上升值和下降值,这就是 iOS 似乎假定为显示文本的垂直“边界框”。

由于缺乏更好的解决方案,我一直在使用(非常丑陋的)hack 来修改 UIFont 只读属性 ascender行高

文件UIFont+Alignment.h:

#import <UIKit/UIKit.h>

@interface UIFont (Alignment)

- (void)ensureCorrectFontAlignment;

@end

文件UIFont+Alignment.m:

#import "UIFont+Alignment.h"
#import <objc/runtime.h>
#import <objc/message.h>

static NSHashTable *adjustedFontsList;

@implementation UIFont (Alignment)

- (void)ensureCorrectFontAlignment
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
adjustedFontsList = [NSHashTable hashTableWithOptions:NSHashTableWeakMemory];
});

@synchronized (adjustedFontsList) {

if ([adjustedFontsList containsObject:self]) {
return;
}
else if ([self.fontName containsString:@"Hiragino"]) {

SEL originalAscenderSelector = @selector(ascender);
Method originalAscenderMethod = class_getInstanceMethod([UIFont class], originalAscenderSelector);
SEL originalLineHeightSelector = @selector(lineHeight);
Method originalLineHeightMethod = class_getInstanceMethod([UIFont class], originalLineHeightSelector);

id result = method_invoke(self, originalAscenderMethod, nil);
CGFloat originalValue = [[result valueForKey:@"ascender"] floatValue];
[result setValue:@(originalValue * 1.15) forKey:@"ascender"];

result = method_invoke(self, originalLineHeightMethod, nil);
originalValue = [[result valueForKey:@"lineHeight"] floatValue];
[result setValue:@(originalValue * 1.25) forKey:@"lineHeight"];

[adjustedFontsList addObject:self];
}
}
}

@end

要应用,只需导入标题并在创建新字体实例后调用[myUIFont ensureCorrectFontAlignment]

关于ios - 系统字体 "Hiragino Sans"显示为剪裁的上升和下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44374358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com