drawInRect:withAttributes文本中心垂直或放置一些填充

Mad*_*dhu 13 objective-c uikit ios ios6 ios7

我正在使用drawInRect:withAttributes将文本添加到iOS 7中的pdf.我需要将文本垂直居中在CGRect内部,或者至少我需要在CGRect边框和文本之间保留一些间隙/填充.否则文字看起来太靠近盒子了.这样做有什么属性吗?如果不是最好的方法是什么?以下是我的代码.
我试过NSBaselineOffsetAttributeName,但它只增加了每一行之间的差距,但没有增加到rect边界的间隙.
谢谢

 CGContextRef    currentContext = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(currentContext, bgColor.CGColor);
CGRect renderingRect = CGRectMake(startPoint.x, startPoint.y, width, height);
CGContextFillRect(currentContext, renderingRect);

NSDictionary *attributes = @{ NSFontAttributeName: font,
                              NSForegroundColorAttributeName: fgColor,
                              };

[textToDraw drawInRect:renderingRect  withAttributes:attributes];
Run Code Online (Sandbox Code Playgroud)

Wil*_*che 17

以下是基于@ Merlevede的回答并使用新API在iOS 8(或7+)中执行此操作的方法:

    NSString *string = ....
    NSDictionary *attributes = ....
    CGSize size = [string sizeWithAttributes:attributes];

    CGRect r = CGRectMake(rect.origin.x,
                          rect.origin.y + (rect.size.height - size.height)/2.0,
                          rect.size.width,
                          size.height);


    [string drawInRect:r withAttributes:attributes];
Run Code Online (Sandbox Code Playgroud)


Mer*_*ede 9

首先,您需要计算文本的高度,使用此信息和边界矩形的高度,您可以轻松计算新矩形以使文本居中.

我将分享一段代码,用于垂直居中.在我的情况下,我使用不同的drawInRect函数(drawInRect:withFont ...),我sizeWithFont用来计算文本的大小.你可以调整这段代码来使用你已经使用过的函数(带属性),或者使用我在这里发布的函数.

UIFont *font = [UIFont systemFontOfSize:14];
CGSize size = [text sizeWithFont:font];
if (size.width < rect.size.width)
{
    CGRect r = CGRectMake(rect.origin.x, 
                          rect.origin.y + (rect.size.height - size.height)/2, 
                          rect.size.width, 
                          (rect.size.height - size.height)/2);
    [text drawInRect:r withFont:font lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentLeft];
}
Run Code Online (Sandbox Code Playgroud)


Fre*_*uid 5

Swift 3解决方案:

extension NSString {
    func drawVerticallyCentered(in rect: CGRect, withAttributes attributes: [String : Any]? = nil) {
        let size = self.size(attributes: attributes)
        let centeredRect = CGRect(x: rect.origin.x, y: rect.origin.y + (rect.size.height-size.height)/2.0, width: rect.size.width, height: size.height)
        self.draw(in: centeredRect, withAttributes: attributes)
    }
}
Run Code Online (Sandbox Code Playgroud)