gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:14:43 24 4
gpt4 key购买 nike

我正在尝试通过这样做向 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 的问题,而且它假定已计算出正确的偏移量,因此文本写入正确的位置。

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

P.S: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);

最佳答案

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

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

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

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

word wrapping in Magick++

关于c++ - 如何在 Magick++ 中为文本添加自动换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34352420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com