我正在使用drawInRect:withAttributes在iOS 7中为pdf添加文本.我需要将文本垂直居中在CGRect中,或至少我需要在CGRect边框和文本之间保留一些间隙/填充.否则文字看起来更接近盒子.有什么属性可以做到吗?如果不是最好的方法呢?以下是我的代码
我试过NSBaselineOffsetAttributeName,但它只增加了每一行之间的差距,而不是与rect的边界的差距.
我试过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];
解决方法
首先,您需要计算文本的高度,使用此信息和边框矩形的高度,您可以轻松计算新的矩形以使文本居中.
我将分享一段我用来垂直居中的代码.在我的情况下,我使用一个不同的drawInRect函数(drawInRect:withFont …),我使用sizeWithFont来计算文本的大小. YOu会调整这个代码来使用你已经使用的函数(带有属性),或者使用我在这里发布的函数.
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];
}