【问题标题】:How to add word wrapping to texts in Magick++如何在 Magick++ 中为文本添加自动换行
【发布时间】:2016-03-24 23:22:30
【问题描述】:

我正在尝试通过这样做在 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);
image.annotate("HelloWorld!", NorthWestGravity);

方法二:

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 的问题,而且它假定已计算出正确的偏移量,因此将文本写入正确的位置。

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

PS:ImageMagick 使用 caption 选项自动换行,但我找不到 caption在 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);

【问题讨论】:

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


    【解决方案1】:

    最好的办法是阅读caption.c 源代码,了解自动换行是如何实现的。这将使您的应用程序拥有完全控制权。

    另一种选择是使用PANGO: 协议。这将使您的内容作者能够完全控制自动换行、格式和许多其他字体显示功能。

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

    #include <Magick++.h>
    
    using namespace Magick;
    
    int main(int argc, const char * argv[]) {
        InitializeMagick(argv[0]);
        Image words(Geometry(250,250), Color("white"));
        words.backgroundColor(Color("lime")); // might not be needed.
        words.font("Avenir-Heavy");
        words.fillColor(Color("firebrick"));
        words.strokeColor(Color("yellow"));
        words.read("CAPTION:Hello World!"); // <---- CAPTION: protocol
        words.write("/tmp/words.jpg");
        return 0;
    }
    

    【讨论】:

    • 又是一个好答案!你怎么知道这一切?!?!我添加了一个基于字体大小的脏边界控件,因为我找不到自动换行。
    • 很高兴这对您有所帮助,但真正要归功于 Anthony Thyssen 和他出色的 body of work。
    猜你喜欢
    • 2018-04-19
    • 1970-01-01
    • 2014-07-10
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    相关资源
    最近更新 更多