2012年5月14日月曜日

NSMutableAttributedString

typeがlinkのpostはtitleを青字の下線で表示すべく色々調べたけど普通にやっても無理みたいでcore text?使わんといかんらしい。とりあえずいろんなサイトから切り貼りでUITextViewのサブクラス作ってみた。

- (id)initWithFrame:(CGRect)frame string:(NSString *)string
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
  NSMutableDictionary *attrDic=[NSMutableDictionary dictionaryWithCapacity:0];
  CTFontRef ctFont=CTFontCreateWithName((__bridge CFStringRef)@"Helvetica",21, NULL);
  [attrDic setObject:(__bridge id)ctFont forKey:(NSString *) kCTFontAttributeName];
  [attrDic setObject:(__bridge id)[UIColor blueColor].CGColor forKey:(NSString *)kCTForegroundColorAttributeName];
  [attrDic setObject:[NSNumber numberWithInt:(int)kCTUnderlineStyleSingle] forKey:(NSString *)kCTUnderlineStyleAttributeName];
  NSMutableAttributedString *linkedText=[[NSMutableAttributedString alloc]initWithString:string attributes:attrDic];
  CGMutablePathRef path=CGPathCreateMutable();
  CTFramesetterRef framesetter= CTFramesetterCreateWithAttributedString((__bridge CFMutableAttributedStringRef)linkedText);;
  CGPathAddRect(path, NULL, self.bounds);
  ctFrame=CTFramesetterCreateFrame(framesetter,CFRangeMake(0, [linkedText length]),path,NULL);
  CGPathRelease(path);
  //self.text=string;self.font=[UIFont fontWithName:@"Helvetica" size:21];self.textColor=[UIColor clearColor];
    }
    return self;
}
- (void)drawRect:(CGRect)rect
{
  CGContextRef context;
    context=UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0, CGRectGetHeight(self.bounds));
    CGContextScaleCTM(context, 1.0f, -1.0f);
    CTFrameDraw(ctFrame, context);
    CGContextRestoreGState(context);
}


UITextViewのサブクラスである必要はなさそうやけど一応。contentSize.height取るために透明色でtextセットしてみたけど、core textのものとは微妙に文字幅、行間が異なるみたいでなんかずれる。ちょっと調べる。
週末は麺や天啓でつけ麺。つけ麺自体はそこそこやけど、〆にスープ割りだけじゃなくて雑炊も選べて、これが実に美味い。今月まだ6杯目。ペースが遅い。

0 件のコメント:

コメントを投稿