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

我正在使用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];

解决方法

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

我将分享一段我用来垂直居中的代码.在我的情况下,我使用一个不同的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];
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...