LoginSignup
76

More than 5 years have passed since last update.

posted at

updated at

UILabelに画像を表示する

UILabelにはNSAttributedStringが指定できるので画像も表示してみる。

NSAttributedStringで画像というとCoreTextあたりで場所を確保して自分で描画とか結構ややこしいんだけど、UILabelなどには結局使えない。その代わりNSTextAttachmentが付いたのでこれをつかって画像を表示してしまおうってお話。

こんな感じ
kobito.1385037314.031520.png

要はNSTextAttachmentを使ってNSAttributedStringに入れればよいというだけ。
かいつまんで書くと以下な感じ。

nsas+image.h


@interface NSMutableAttributedString (atimg)
-(void)insertImage:(UIImage*)image bounds:(CGRect)bounds atIndex:(NSUInteger)index;
@end

nsas+image.m


@implementation NSMutableAttributedString (atimg)

-(void)insertImage:(UIImage*)image bounds:(CGRect)bounds atIndex:(NSUInteger)index;

{
    NSTextAttachment *at = [[NSTextAttachment alloc] init];
    at.image = image;
    at.bounds = bounds;
    NSAttributedString *ns = [NSAttributedString attributedStringWithAttachment:at];
    // unicode : NSAttachmentCharacter = 0xFFFC

    [self insertAttributedString:ns atIndex:index];
}

@end

sample

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:@"ミクさんフリフリ"];
    [as insertImage:[UIImage imageNamed:@"miku"] bounds:CGRectMake(-2, -10, 40, 40) atIndex:4];
    _lbl.attributedText = as;

}

boundsのorigin,sizeで位置や大きさの指定可能。
attributedTextで使えるってことはUITextViewなど、UIKitでNSAttributedStringが指定出来るものでは使用可能。

attachmentなUnicodeは0xFFFC (OBJECT REPLACEMENT CHARACTER) で用意してあるのよね。

こう面倒なことしなくても出したいだけならhtml->NSAttributedStringにimgでもいくのでは・・

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
What you can do with signing up
76