ios - 绘制矩形 : withAttributes text center vertically or put some padding

标签 ios objective-c ios6 ios7 uikit

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

相关文章:

iphone - 如何为不可编辑的 UITextView 设置光标位置?

ios - 如何获取 NSManagedObjectId 并检索数据

ios - Unity3d IOS 应用程序 : Error opening third-party application using Application. OpenURL

c++ - 从 NSData 存储和恢复 std::vector

ios - 刷新 map 后错误的图像 MKAnnotationView

ios - 如何查看iOS版本是iOS 6?

ios - UINavigationController pushViewController 在中途暂停/卡住

ios - 如何优化 cellForRowAtIndexPath : code

ios - dismissViewControllerAnimated 不工作

objective-c - 自迁移以来导航栏和表格 View 之间的黑条