NSAttributedString を使用して、ユーザーの検索の一致するクエリで文字列の一部を強調表示することを計画していました。ただし、 iOS に相当するものが見つかりませんNSBackgroundColorAttributeName
— there's no kCTBackgroundColorAttributeName
. NSForegroundColorAttributeName
のようになるようなものは存在するのkCTForegroundColorAttributeName
だろうか?
2 に答える
いいえ、そのような属性は Core Text には存在しません。シミュレートするには、テキストの下に独自の長方形を描画する必要があります。
基本的に、文字列内の特定の範囲を埋める四角形を特定する必要があります。CTFramesetter
を生成する を使用してレイアウトを行う場合は、CTFrame
および を使用してその線と原点を取得する必要がありCTFrameGetLines
ますCTFrameGetLineOrigins
。
次に、行を繰り返し、 を使用CTLineGetStringRange
して、強調表示する範囲の一部である行を見つけます。四角形を塗りつぶすには、CTLineGetTypographicBounds
(高さ) とCTLineGetOffsetForStringIndex
(水平方向のオフセットと幅) を使用します。
NSBackgroundColorAttributeName は iOS 6 で利用可能で、次の方法で使用できます。
[_attributedText addAttribute: NSBackgroundColorAttributeName value:[UIColor yellowColor] range:textRange];
[_attributedText drawInRect:rect];
drawInRect:
NSBackgroundColorAttributeName と、iOS 6 でサポートされているすべての NS*AttributeNames をサポートします。
CTFrameDraw() では、背景テキストの色はサポートされていません。
コード:
- (void)drawRect:(CGRect)rect {
// First draw selection / marked text, then draw text
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[_attributedText drawInRect:rect];
CGContextRestoreGState(context);
// CTFrameDraw(_frame, UIGraphicsGetCurrentContext());
}