属性付きテキストによるテキストの装飾(前編)

NSUnderlineStyleAttributeName, NSStrikethroughStyleAttributeName
下線や取り消し線のスタイルを示すNSNumberオブジェクトです。
スタイルは、NSUnderlineStyleとして定義されている以下の値を使用して指定します。なお、NSUnderlineStyleNaneとNSUnderlineStyleSingle以外は、iOS 6では使えません。
[表2] 下線、取り消し線のスタイル(NSUnderlineStyle)
| 定義 | 値 | スタイル |
|---|---|---|
| NSUnderlineStyleNone | 0x00 | なし |
| NSUnderlineStyleSingle | 0x01 | 単一線 |
| NSUnderlineStyleThick | 0x02 | 太線 |
| NSUnderlineStyleDouble | 0x09 | 二重線 |
| NSUnderlinePatternSolid | 0x0000 | 実線 |
| NSUnderlinePatternDot | 0x0100 | 点線 |
| NSUnderlinePatternDash | 0x0200 | 破線(鎖線) |
| NSUnderlinePatternDashDot | 0x0300 | 一点鎖線 |
| NSUnderlinePatternDashDotDot | 0x0400 | 二点鎖線 |
| NSUnderlineByWord | 0x8000 | 単語の下のみ |
ここで、スタイル(NSUnderLineStyleXxx)、パターン(NSUnderlinePatternXxx)、単語ごとの指定(NSUnderlineByWord)は、OR加算して使用します。
例えば、二重点線を単語の下のみに引くには、以下のコードを記述します(ソースコード27)。生成したテキストを表示した結果が下図です(図8)。
[ソースコード27] 下線付きテキストの生成
NSUnderlineStyle underlineStyle =
NSUnderlineStyleDouble | NSUnderlinePatternDot | NSUnderlineByWord;
NSAttributedString *underlineText =
[[NSAttributedString alloc] initWithString:@"下線付きテキスト Underline"
attributes:@{NSUnderlineStyleAttributeName: @(underlineStyle)}];
図8: 下線付きテキスト
取り消し線を表示するには、NSUnderlineStyleAttributeNameの代わりにNSStrikethroughStyleAttributeNameを使用します。
NSUnderlineColorAttributeName,
NSStrikethroughColorAttributeName(iOS 7以降)
下線、取り消し線の色を示すUIColorオブジェクトです。
NSStrokeColorAttributeName
縁取りの色を示すUIColorオブジェクトです。
指定がない場合、NSFourgroundColorが指定する色が縁取りに使用されます。
NSStrokeWidthAttributeName
縁取りの太さ(フォントのポイントサイズに対するパーセンテージ)を示すNSNumber(float)オブジェクトです。
設定する値の符号によりテキストの塗りつぶし設定が異なります(表3)。
[表3] 設定値の符号と塗りつぶし、枠線の関係
| 値 | 塗りつぶし | 枠線 |
|---|---|---|
| 0 | あり | なし |
| 正の値 | なし | あり |
| 負の値 | あり | あり |
[ソースコード28] 縁取りテキストを生成
// 塗りつぶしのみのテキスト(通常の表示)
NSAttributedString *filledText =
[[NSAttributedString alloc] initWithString:@"塗りつぶしと縁取り"
attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
// 縁取りのみのテキスト
NSAttributedString *outlineText =
[[NSAttributedString alloc] initWithString:@"塗りつぶしと縁取り"
attributes:@{NSStrokeColorAttributeName: [UIColor blackColor],
NSStrokeWidthAttributeName: @(5.0f)}]; // 正の値
// 縁取りと塗りつぶしのテキスト
NSAttributedString *filledOutlineText =
[[NSAttributedString alloc] initWithString:@"塗りつぶしと縁取り"
attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor],
NSStrokeColorAttributeName: [UIColor blackColor],
NSStrokeWidthAttributeName: @(-5.0f)}]; // 負の値
上記の例で生成した属性付きテキストを表示した結果が下図です(図9)。
図9: 塗りつぶし(上)、縁取り(中)、塗りつぶしと縁取り(下)
属性付きテキストに使用できる属性はこれだけではありません。残りの属性については次回解説します。




