Font size in pixels

前端 未结 7 659
陌清茗
陌清茗 2020-11-29 17:14

On an iPhone how do I calculate the size of a character in pixels for a given point size?

7条回答
  •  感情败类
    2020-11-29 17:51

    The easiest way to get the pixel height for a given font and size is to use the boundingRect method on NSString. (I'm using @"Ap" here to make sure it contains a descender and an ascender.)

    - (CGFloat)heightForFont:(UIFont *)font
    {
        NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
        CGRect boundingRect = [@"Ap" boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:context];
        return boundingRect.size.height;
    }
    

提交回复
热议问题