2010-05-08 100 views
4

我使用開羅(pycairo專門)繪製圖形,我需要知道如何在圈內繪製文本而不重疊,通過將其保留在圈子的邊界內。我有這個簡單的代碼片段,吸引了一個字母「a」內圓:如何使用開羅將文字保留在圓圈內?

''' 
Created on May 8, 2010 

@author: mrios 
''' 
import cairo, math 

WIDTH, HEIGHT = 1000, 1000 

#surface = cairo.PDFSurface ("/Users/mrios/Desktop/exampleplaces.pdf", WIDTH, HEIGHT) 
surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, WIDTH, HEIGHT) 
ctx = cairo.Context (surface) 

ctx.scale (WIDTH/1.0, HEIGHT/1.0) # Normalizing the canvas 


ctx.rectangle(0, 0, 1, 1) # Rectangle(x0, y0, x1, y1) 
ctx.set_source_rgb(255,255,255) 
ctx.fill() 

ctx.arc(0.5, 0.5, .4, 0, 2*math.pi) 
ctx.set_source_rgb(0,0,0) 
ctx.set_line_width(0.03) 
ctx.stroke() 

ctx.arc(0.5, 0.5, .4, 0, 2*math.pi) 
ctx.set_source_rgb(0,0,0) 
ctx.set_line_width(0.01) 
ctx.set_source_rgb(255,0,255) 
ctx.fill() 
ctx.set_source_rgb(0,0,0) 

ctx.select_font_face("Georgia", 
      cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) 
ctx.set_font_size(1.0) 
x_bearing, y_bearing, width, height = ctx.text_extents("a")[:4] 
print ctx.text_extents("a")[:4] 
ctx.move_to(0.5 - width/2 - x_bearing, 0.5 - height/2 - y_bearing) 
ctx.show_text("a") 

surface.write_to_png ("/Users/mrios/Desktop/node.png") # Output to PNG 

的問題是,我的唱片公司有字符變量量(20的限制),我需要設置的大小字體動態。無論圓圈的大小還是標籤的大小,它都必須放在圓圈內。另外,每個標籤都有一行文字,沒有空格,沒有換行符。

有什麼建議嗎?

+0

P.S.調用set_source_rgb()時應使用浮點數(0-1.0)。請參閱http://cairographics.org/documentation/pycairo/2/reference/context.html#class-context – dkamins 2011-11-04 22:30:37

回答

3

我有一個類似的問題,我需要調整字體的大小,以保持我的對象的名稱在矩形的邊界內,而不是圓。我使用了一個while循環,並不斷檢查字符串的文本範圍大小,減小字體大小直到適合。

在這裏,我做了:(這是使用C++下的Kylix,Delphi衍生物)。

double fontSize = 20.0; 
    bool bFontFits = false; 

    while (bFontFits == false) 
    { 
     m_pCanvas->Font->Size = (int)fontSize; 
     TSize te = m_pCanvas->TextExtent(m_name.c_str()); 
     if (te.cx < (width*0.90)) // Allow a little room on each side 
     { 
      // Calculate the position 
      m_labelOrigin.x = rectX + (width/2.0) - (te.cx/2); 
      m_labelOrigin.y = rectY + (height/2.0) - te.cy/2); 
      m_fontSize = fontSize; 
      bFontFits = true; 
      break; 
     } 
     fontSize -= 1.0; 
} 

當然,這不顯示錯誤檢查。如果矩形(或圓圈)太小,則必須跳出循環。

3

由於圓圈的大小並不重要,因此應該按照與代碼相反的順序繪製它們。

  1. 打印屏幕上的
  2. 文本計算文本邊界(使用文字程度)
  3. 周圍繪製僅僅是從文本稍大一點的文字了一圈。