2015-07-20 34 views
0

我使用的例子 http://developer.xamarin.com/recipes/ios/graphics_and_drawing/core_text/draw_unicode_text_with_coretext/使用MonoTouch.CoreText繪製多行文本

Using MonoTouch.CoreText to draw text fragments at specific coordinaates

繪製了UIView的文本行。

現在我需要擴展它來繪製多行文本。基本上很簡單。在Draw()方法中,我將多行字符串Text分割爲「\ n」,並將任意一行添加newLineDY給Y調用DrawTextLine()。 唯一的問題是任何新的線條繪製都會在X畫上一個結束:

AAA BBB CCC

如何避免X位移?可以重置嗎?怎麼樣?我嘗試爲任何行應用負面的DX,但我不知道應用的正確值。

private const float newLineDY = 40; 
public override void Draw() 
    { 
     string[] lines = Text.Split("\n".ToCharArray()); 
     float lx = X; 
     float ly = Y; 
     foreach (string line in lines) 
     { 
      DrawTextLine(line, lx, ly); 
      //lx -= 100;  // negative DX 
      ly += newLineDY; 
     } 
    } 
    private void DrawTextLine(string text, float x, float y) 
    { 
     CGContext gctx = UIGraphics.GetCurrentContext(); 
     gctx.SaveState(); 
     gctx.TranslateCTM(x, y); 
     //gctx.TextPosition = new CGPoint(x, y); 
     gctx.ScaleCTM(1, -1); 
     //gctx.RotateCTM((float)Math.PI * 315/180); 

     gctx.SetFillColor(UIColor.Black.CGColor); 

     var attributedString = new NSAttributedString(text, 
      new CTStringAttributes 
      { 
       ForegroundColorFromContext = true, 
       Font = new CTFont("Arial", 24) 
      }); 

     using (CTLine textLine = new CTLine(attributedString)) 
     { 
      textLine.Draw(gctx); 
     } 
     gctx.RestoreState(); 
    } 

Thaks!

回答

1

我一直在使用attributedString.DrawString解決(新CGPoint(X,Y)),一個更簡單的API,這裏建議

http://monotouch.2284126.n4.nabble.com/Using-MonoTouch-CoreText-to-draw-text-fragments-at-specific-coordinates-td4658531.html

所以我的代碼變成了:

private const float newLineDY = 40; 
    public override void Draw() 
    { 
     string[] lines = Text.Split("\n".ToCharArray()); 
     float lx = X; 
     float ly = Y; 
     foreach (string line in lines) 
     { 
      DrawTextLine(line, lx, ly); 
      ly += newLineDY; 
     } 
    } 
    private void DrawTextLine(string text, float x, float y) 
    { 
     NSAttributedString attributedString = new NSAttributedString(
      text, 
      new CTStringAttributes 
      { 
       ForegroundColorFromContext = true, 
       Font = new CTFont("Arial", 24) 
      }); 
     attributedString.DrawString(new CGPoint(x, y)); 
    }