如何在Magick ++中为文本添加自动换行

时间:2015-12-18 09:34:41

标签: c++ image-processing imagemagick word-wrap magick++

我试图通过这样做在Magick ++中为图像添加文本:

方法1:

Magick::Image image(Magick::Geometry(800,800),Magick::Color("white"));
Magick::Color color(0,0,0,0);
image.font("Waree");
image.fontPointsize(36);
image.strokeColor(color);
image.fillColor(color);
image.annotate("HelloWorld!", NorthWestGravity);

方法2:

Magick::Image image(Magick::Geometry(800,800),Magick::Color("white"));
Magick::Color color(0,0,0,0);
std::list<Magick::Drawable> text_draw_list;
text_draw_list.push_back(Magick::DrawableViewbox(0,0,image.columns(), image.rows()));
text_draw_list.push_back(Magick::DrawableFont("Waree", (Magick::StyleType)NormalStyle, 400, (Magick::StretchType)NormalStretch ));
text_draw_list.push_back(Magick::DrawablePointSize(36));
//Manual offsets
text_draw_list.push_back(Magick::DrawableText(0, 200, "HelloWorld!"));
text_draw_list.push_back(Magick::DrawableStrokeColor(color));
text_draw_list.push_back(Magick::DrawableFillColor(color));
image.draw(text_draw_list);

方法1在给定重力的情况下计算最佳偏移量,但如果文本超出图像范围则没有任何自动换行。

方法2有方法1的问题加上它假定已经计算了正确的偏移量,因此文本写在正确的位置。

如何将自动换行添加到2种方法中的任何一种,但最好是方法1?

PS:ImageMagick使用 标题 选项自动换行,但我找不到 标题 在Magick ++。

编辑:基于字体大小的丑陋边界控制。

Magick::Image image(Magick::Geometry(800,800),Magick::Color("white"));
Magick::Color color(0,0,0,0);
image.font("Waree");
image.fontPointsize(36);
image.strokeColor(color);
image.fillColor(color);
std::string txt = "HelloWorld!";
Magick::TypeMetric typeMetrics;
double fontSize = 36;
image.fontTypeMetrics(txt, &typeMetrics);
while(fontSize > 0)
{
 if(typeMetrics.textWidth() >= image.columns() || typeMetrics.textHeight() >= image.rows())
 {
  fontSize--;
  image.fontTypeMetrics(txt, &typeMetrics);
 }
}
image.annotate(txt, NorthWestGravity);

1 个答案:

答案 0 :(得分:2)

最好的办法是阅读caption.c来源,并了解如何实现自动换行。这将允许您的应用程序完全控制。

另一种选择是使用function updateTextInput1(val) { alert(val); document.getElementById('num1').value = val; }协议。这将允许您的内容作者完全控制自动换行,格式和许多其他字体显示功能。

但是对于最快的方法,正如您所提到的, caption 已经这样做了。但是标题不是一种方法,而是一种文件协议。

<input class="inputRange" type="range" min="0" max="100" onchange="updateTextInput1(this.value)" />
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />

word wrapping in Magick++