我是使用开罗(特别是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),我需要动态设置字体的大小。无论圆的大小或标签的大小,它都必须安装在圆圈内。另外,每个标签都有一行文本,没有空格,没有线路断裂。

有建议吗?

有帮助吗?

解决方案

我也有一个类似的问题,我需要调整字体的大小,以使对象的名称保持在矩形的边界,而不是圆圈的边界内。我使用了一段时间的循环,并一直检查字符串的文本范围,从而降低了字体大小,直到合适为止。

在这里我所做的:(这是在delphi衍生物Kylix下使用的C ++)。

    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;
}

当然,这不会显示错误检查。如果矩形(或您的圆形)太小,则必须脱离循环。

其他提示

由于圆的大小并不重要,因此您应该以相反的顺序绘制它们。

  1. 在屏幕上打印文本
  2. 计算文本边界(使用文本范围)
  3. 在文本周围绘制一个圆圈,与文本相比要大一点。
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top