LoginSignup
11
11

More than 5 years have passed since last update.

drawWithRectでTail Truncationする(ParagraphではなくRectで)

Last updated at Posted at 2015-06-06

drawInRect などでStringを描画する場合(UILabelなどでもそうだが)、Paragraphが対象の場合は、指定範囲で途中で切れたStringに自動的に...をつけてくれるTail Truncationにするには、下記のようにlineBreakModeにByTruncatingTailを指定したAttributeを作ればいい。

let style = NSMutableParagraphStyle()
style.lineBreakMode =.ByTruncatingTail
style.alignment = NSTextAlignment.Left
let stringAttrubute = [
    NSParagraphStyleAttributeName: style
]

しかし、Paragraph は Word Wrapping して同時に描画範囲内で Tail Truncation したい場合どうすればいいのだろう。

例えば、下の図のような感じにしたい。図の文章のあとにまだ文章は続いているが、draw範囲はそれより小さいのだ。
fig01.png

ちなみに以下のような指定はエラーになる。

style.lineBreakMode = .ByTruncatingTail | .ByWordWrapping

↓結論
drawWithRect のoptionsの指定に TruncatesLastVisibleLine があるからこれを使えばいいと分かったのでのメモ。
NSMutableParagraphStyle は ByWordWrapping にして、drawWithRect でTruncatesLastVisibleLine 指定。

let style = NSMutableParagraphStyle()
style.lineBreakMode =.ByWordWrapping
style.alignment = NSTextAlignment.Left
let stringAttrubute = [
    NSParagraphStyleAttributeName: style
]
let sampleText = "このStringは、このように...(略)...するようにしたい。途中で改行がはいるのである。\nどうすればいいのだろう?あ、できた!\nそして、まだまだStringは続く....(略)...."
sampleText.drawWithRect(
    CGRectMake(0,0,800,300), 
    options: .UsesLineFragmentOrigin | .TruncatesLastVisibleLine,
    attributes: stringAttrubute  as [NSObject : AnyObject],
    context: nil)

ちなみに、Objective-Cでは下記だけでこれができていた(ような気がする)。

[sampleText drawInRect:CGRectMake(0,0,800,300)
                       withFont: font
                       lineBreakMode:NSLineBreakByTruncatingTail];
11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11