Search code examples
objective-cswiftuiviewuifontcgrect

Determine UIFont size with CGSize Points or Pixels


I can make a CGRect with an exact defined PointSize e.g (20x20) and on this way i can exactly calculate the real size (cm or inch) on the Screen.

-(void) drawRect:(CGRect)rect{    
  [super drawRect:rect];  
  CGRect rectangle = CGRectMake(0, 0, 20, 20);
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
  CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
  CGContextFillRect(context, rectangle);
}

I would like to determine the size of the UIFont (always only one Charackter "A..Z" or "1..9") somehow in a simular way, so that i can calculate at least the real height on the Screen.

Is it possible to calculate the Font size from CGSize to UIfont Size, so that it really matches on the screen ?


Solution

  • I have found a Solution for this kind of Problem.
    If you want to have an UIFont to fit a CGRect or a Label, it won't fit the CGRect in the most cases. The Reason are the Font specific paddings. If you want a Font to fit a CGRect, you must know wheter to use a lower or Upper Case Letters, an then to set font.xHeigth or the font.capHeight as font.pointSize. Therefore you'll get a bigger font.pointsize.
    This little CodeSnippet solved my Problem:

    +(CGFloat) fitFontSize:(UIFont*) font{
        CGFloat fontSize = font.pointSize;
        bool fontSizeAdjusted = false;
    
        while (!fontSizeAdjusted) {
            CGFloat xHeight = font.xHeight;
            if( fontSize-xHeight > 0.1 ){
                font = [font fontWithSize:font.pointSize+1];
            }else{
                fontSizeAdjusted = true;
                fontSize = font.pointSize;
            }
        }
        return fontSize;
    }
    

    This Article helped me to learn more about UIFonts