3

色、フォント、サイズ、配置を指定してカスタム文字列を描画しようとしています。

以前はすべて NSMutableAttributedString で動作していましたが、テキスト アラインメントは、非可変バージョンの NSString でのみ動作する段落アラインメントでのみ動作するようです。

したがって、以前のコードを次のように変更する必要がありました。

    //Note : _name variables are provided by my GUI for text, size and font name.

    //Create the String ColorRef
    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
    const CGFloat myColor[] = {_color.r/255.0, _color.g/255.0, _color.b/255.0, 1.0f};
    CGColorRef colorRef = CGColorCreate(rgb, myColor);

    //Setup paragraph Alignment Ref
    CTTextAlignment theAlignment = kCTCenterTextAlignment;
    CFIndex theNumberOfSettings = 1;
    CTParagraphStyleSetting theSettings[1] = {{ kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &theAlignment }};
    CTParagraphStyleRef theParagraphRef = CTParagraphStyleCreate(theSettings, theNumberOfSettings);

    //Prep Font
    NSDictionary *fontAttributes = [NSDictionary dictionaryWithObjectsAndKeys: _fontName, (NSString *)kCTFontFamilyNameAttribute,
                                    [NSNumber numberWithFloat:_fontSize], (NSString *)kCTFontSizeAttribute,
                                    nil];
    CTFontRef font = [self newFontWithAttributes:fontAttributes];

    //Prepare String Attributes
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: (id)font, (NSString *)kCTFontAttributeName,
                                                [NSNumber numberWithFloat:_fontSize], (NSString *)kCTFontSizeAttribute,
                                                                 (id)theParagraphRef, (NSString*)kCTParagraphStyleAttributeName, 
                                                                            colorRef, (NSString *)kCTForegroundColorAttributeName, nil];

    //Create the Attributed String
    NSAttributedString *myString = [[NSAttributedString alloc] initWithString:_textString
                                                                   attributes: attributes];

しかし、テキストの配置はまだ機能しません。それ以外は問題ありませんが、テキストは左揃えのままです。

なんで ?

編集:私の文字列はそれぞれ、CATextLayerのサブクラスであるクラス内に作成されます。これらの各 TextLayer は、サブレイヤーとして CALayer に追加されます。更新時に、サブレイヤーに変換マトリックスを適用し、setNeedsDisplay. これは、画面にテキストを表示する方法です。CTParagraphStyleRef セットが機能しない理由がここにあるのではないでしょうか?

4

1 に答える 1

4

私が設定したParagraphStyleが機能しない理由はわかりませんが、私のために機能する解決策を見つけたので、誰かが同様の問題に遭遇した場合に備えて投稿します:

  • 私のクラスはCATextLayerをサブクラス化しています。これは、私の質問で言及することが重要だと思います(私の悪いことですが、編集します)。
  • CATextLayerクラス内で、質問に示されているコードを使用して文字列を作成します。
  • 次に、を使用しself.alignmentMode = kCAAlignmentCenter;てテキストを希望どおりに配置します。
  • 次に、各文字列が表示用にCALAyerに追加されます

また、コードを改善してこの解決策を見つけるのに役立つAttributedStringsに関するこの非常に優れたガイドも見つけました。

于 2011-11-21T16:07:05.047 に答える