12

NSAttributedString を使用して、ユーザーの検索の一致するクエリで文字列の一部を強調表示することを計画していました。ただし、 iOS に相当するものが見つかりませんNSBackgroundColorAttributeName— there's no kCTBackgroundColorAttributeName. NSForegroundColorAttributeNameのようになるようなものは存在するのkCTForegroundColorAttributeNameだろうか?

4

2 に答える 2

8

いいえ、そのような属性は Core Text には存在しません。シミュレートするには、テキストの下に独自の長方形を描画する必要があります。

基本的に、文字列内の特定の範囲を埋める四角形を特定する必要があります。CTFramesetterを生成する を使用してレイアウトを行う場合は、CTFrameおよび を使用してその線と原点を取得する必要がありCTFrameGetLinesますCTFrameGetLineOrigins

次に、行を繰り返し、 を使用CTLineGetStringRangeして、強調表示する範囲の一部である行を見つけます。四角形を塗りつぶすには、CTLineGetTypographicBounds(高さ) とCTLineGetOffsetForStringIndex(水平方向のオフセットと幅) を使用します。

于 2011-07-31T16:33:05.373 に答える
4

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());

}
于 2012-10-18T18:43:51.313 に答える