如何使用NSString drawInRect来居中文本? [英] How to use NSString drawInRect to center text?

查看:190
本文介绍了如何使用NSString drawInRect来居中文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 NSRect ?中绘制一个 NSString

我开始:(从自定义视图的drawRect方法中提取)

I've started off with: (an extract from the drawRect method of my custom view)

NSString* theString = ...
[theString drawInRect:theRect withAttributes:0];
[theString release];

现在我假设我需要设置一些属性。我已经看了一下苹果的Cocoa文档,但它有点压倒性,并找不到任何东西如何添加段落样式的属性。

Now I'm assuming I need to set up some attributes. I've had a look through Apple's Cocoa documentation, but it's a bit overwhelming and can't find anything for how to add paragraph styles to the attributes.

此外,我只能找到水平对齐方式,垂直对齐方式?

Also, I can only find horizontal alignment, what about vertical alignment?

推荐答案

垂直对齐你必须自己做((视图的高度+字符串的高度)/ 2)。水平对齐可以:

Vertical alignment you'll have to do yourself ((height of view + height of string)/2). Horizontal alignment you can do with:

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];
[myString drawInRect:someRect withAttributes:attr];

这篇关于如何使用NSString drawInRect来居中文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆