CFAttributedStringSetAttributeで、フォントを変更、アラインの変更などなど 2010/09/03

CGContextRefにいろいろ描画していて、さらに文字列を表示しようとしていろいろ四苦八苦。
表示する分には簡単に調べてできたけど、中央に表示したいと思い、やりはじめるといろいろはまったのでした。
とりあえず、iphone sdk4.0がターゲットです。

(1)iphoneだと、文字がひっくりかえるの防ぐ


CGAffineTransform transform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(context, transform);


(2)フォントを変更。
※CTFontCreateWithNameって、フォントによっては時間がかかってるようにみえた.....

CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica"), 48., NULL);// これでも日本語okだった.....
CFAttributedStringSetAttribute(attrString, CFRangeMake(0,[str length]), kCTFontAttributeName, font);
CFRelease(font);


(3)真ん中にそろえる

CTTextAlignment alignment = kCTCenterTextAlignment;// kCTJustifiedTextAlignment
CTParagraphStyleSetting _settings[] = { {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment} };
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(_settings, sizeof(_settings) / sizeof(_settings[0]));

CFAttributedStringSetAttribute(attrString, CFRangeMake(0, CFAttributedStringGetLength(attrString)), kCTParagraphStyleAttributeName, paragraphStyle);
CFRelease(paragraphStyle);


特に、このサイトの記事によるものです。

ここのスライドショー


参考


コード自分用
{ // このコードがないとひっくりかえるよ
CGAffineTransform transform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(context, transform);
}

CGMutablePathRef path = CGPathCreateMutable();
CGRect bounds = CGRectMake(0.0, 10.0, 320, 200.0);
CGPathAddRect(path, NULL, bounds);
CFStringRef string = (CFStringRef)str;// CFSTR("test");
CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), string);

{ // フォントを変更
CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica"), 48., NULL);// これでも日本語okだった.....
CFAttributedStringSetAttribute(attrString, CFRangeMake(0,[str length]), kCTFontAttributeName, font);
CFRelease(font);
}


{ // アラインを変更
CTTextAlignment alignment = kCTCenterTextAlignment;// kCTJustifiedTextAlignment
CTParagraphStyleSetting _settings[] = { {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment} };
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(_settings, sizeof(_settings) / sizeof(_settings[0]));

CFAttributedStringSetAttribute(attrString, CFRangeMake(0, CFAttributedStringGetLength(attrString)), kCTParagraphStyleAttributeName, paragraphStyle);
CFRelease(paragraphStyle);
}

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0, 0), path, NULL);

CFRelease(attrString);
CFRelease(framesetter);
CTFrameDraw(frame, context);
CFRelease(frame);

: