« 今週のセンスが無い奴にはうちわを | ホーム | 今週の2008年の10大ニュース »

2008年11月27日

Attributed Stringで(リサイズした)画像を出したい。

NSTextAttachmentを使ってNSAttributedStringに画像をはめ込むことが出来るのは知ってたんだけど、最近ふと思いついて初めてちゃんと使ってみた。

	NSFileWrapper* filewrapper = [[[NSFileWrapper alloc] initWithPath:@"..."] autorelease];	
	NSTextAttachment* attachment = [[[NSTextAttachment alloc] initWithFileWrapper:filewrapper] autorelease];

	id text = [NSAttributedString attributedStringWithAttachment:attachment];

こんな風に。だけど、適当に拾ってきた画像だと縦横サイズが不定なので、やたらどでかいファイル持ってこようものなら、際限なく広がってしまってちょっと始末が悪い。最大サイズを指定してそれ以上になったらリサイズするようにしてみたくなった。

pict01.png

つまりこれが、

pict02.png

こうなっちゃったりすると、いやよね奥さんそう思いませんおほほ?という。

でこれが、あれやこれやと試してみてなかなかうまく行かなかった。NSTextAttachmentCellがNSTextAttachmentによって自動的に生成されるに任せていると、元のファイルのサイズでそのまま出てしまう。-[NSTextAttachment attachmentCell]で得られるのはid<NSTextAttachmentCell>で、内部で生成されたNSImageインスタンスを参照するメソッド等は用意されていない。むりくりNSTextAttachmentCell*型にキャストするわけにもいかないので、どうしようかという話になった。

まあ、思いつけばな〜んだの部類すけど、縮小したNSImageを自前で生成してそれを同じく自前で作ったNSTextAttachmentCellに渡してNSTextAttachmentにつなげる、という手はずに乗せたらうまくいったとよ。


NSSize
_size_proportionally(NSSize origSize, NSSize maxSize)
{
	CGFloat zoom = (origSize.width > origSize.height ? maxSize.width / origSize.width : maxSize.height / origSize.height);

	return NSMakeSize(origSize.width * zoom, origSize.height * zoom);
}

- (IBAction)doAction:(id)sender
{
	NSURL *url = [NSURL URLWithString:@"http://icanhascheezburger.files.wordpress.com/2008/11/funny-pictures-always-hold-hands-with-your-kitten.jpg"];
	NSImage *image = [[[NSImage alloc] initWithContentsOfURL:url] autorelease];

	[image setSize:_size_proportionally([image size], NSMakeSize(200, 200))];
    NSTextAttachment* attachment = [[[NSTextAttachment alloc] init] autorelease];
	NSTextAttachmentCell* attachmentCell = [[[NSTextAttachmentCell alloc] initImageCell:image] autorelease];
	
	[attachment setAttachmentCell:attachmentCell];
	
	id text = [NSMutableAttributedString attributedStringWithAttachment:attachment];
	[text addAttribute:NSLinkAttributeName value:url range:NSMakeRange(0, [text length])];
	
	[[textView textStorage] appendAttributedString:text];
}

pict03.png

こうなった。よーしよし。

トラックバック(0)

トラックバックURL: http://foursics.jp/cgi-bin/mt/mt-tb.cgi/229

コメントする