我正在使用 drawInRect : withAttributes 将文本添加到 iOS 7 中的 pdf。我需要在 CGRect 中垂直居中文本,或者至少我需要在 CGRect 边框和文本之间保持一些间隙/填充。否则文本看起来离框太近了。有什么属性可以做到这一点吗?如果不是,最好的方法是什么?下面是我的代码。
我试过 NSBaselineOffsetAttributeName ,但它只会增加每行之间的间隙,但不会增加到矩形边界的间隙。
谢谢
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];
最佳答案
以下是在 iOS 8(或 7+)中如何根据@Merlevede 的回答进行更正并使用新的 API 来做到这一点:
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];
关于ios - 绘制矩形 : withAttributes text center vertically or put some padding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21950556/