itok's Lab

昔の開発ネタを記録として残してます

段落スタイルの設定

文字列を描画したりする場合、NSRect を指定しての描画で「中央揃え」とかはみ出した文字を「...」で省略させたりとか、そういうことの設定には NSMutableParagraphStyle を使います。

まず、揃えに関してはこんな感じ。

-(void)setAlignment:(NSTextAlignment)alignment;
[NSTextAlignment]
NSLeftTextAlignment      : 左揃え
NSRightTextAlignment     : 右揃え
NSCenterTextAlignment    : 中央揃え
NSJustifiedTextAlignment : 均等
NSNaturalTextAlignment   : 自動(デフォルト)

省略関係(というか、文字列が描画領域の幅を越えてしまった時の処理設定)はこう。

-(void)setLineBreakMode:(NSLineBreakMode)mode;
[NSLineBreakMode]
NSLineBreakByWordWrapping     : 単語で折り返し
NSLineBreakByCharWrapping     : 文字で折り返し
NSLineBreakByClipping         : 単に途切れるだけ
NSLineBreakByTruncatingHead   : 冒頭を"..."で省略
NSLineBreakByTruncatingTail   : 末尾を"..."で省略
NSLineBreakByTruncatingMiddle : 中ほどを"..."で省略

たとえば、中央寄せの末尾省略の場合はこうなります。

NSMutableParagraphStyle* style = [[[NSMutableParagraphStyle alloc] init] autorelease];
[style setAlignment:NSCenterTextAlignment];
[style setLineBreakMode:NSLineBreakByTruncatingTail];
NSDictionary* attr = 
    [NSDictionary dictionaryWithObjectsAndKeys:style, NSParagraphStyleAttributeName, nil];
NSAttributedString* astr = 
    [[[NSAttributedString alloc] initWithString:text attributes:attr] autorelease];
[astr drawInRect:rect];

NSMutableParagraphStyle には他にもいろいろ設定できるので、詳しくはリファレンスを参照してくださいませ。