2010-05-08 93 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. 周围绘制仅仅是从文本稍大一点的文字了一圈。
相关问题