Graphicsmagick: How to draw text to fit a specific box (width/height)

我只是一个虾纸丫 提交于 2019-12-10 13:16:38

问题


I'm using GraphicsMagick's node.js module.

In my Node JS application I need to add a text label to an existing image, such that: 1) If the text is longer than the image size, the text auto-wraps around to the next line 2) If the text is not able to fit into the image, the font size of the text is automatically adjusted (reduced) to fit into the box of the image

The available APIs from GraphicsMagick's node.js module are:

gm("img.png").drawText(x, y, text [, gravity])

But this does not provide any options to fit the text into the box per the two requirements above. If I use this API alone I will need to manually break the text, and change the text font size to fit the image, but even for that I will need to first be able to measure the text size. Is there a way to do that?

Any suggestions?

For illustration purpose, below image shows three different text strings that need to fit into the same sized box. Hope it clarifies.


回答1:


I have lost half a day, but can reach solve for this question. I use gm with gm.subClass({ imageMagick: true }). I think you can use it with a few changing for fully resolve your problem.

public createPreview(text: string) {
 this.imageGenerator(800, 600, '#4c4cfc')
  .fill('#FFFFFF')
  .font('../../../client/assets/fonts/GraphikLCG-Bold.woff')
  .fontSize('46')
  .out('-background', '#4c4cfc')
  .out('-size', '400x', 'caption:' + text)
  .out('-gravity', 'center')
  .out('-composite')
  .write('./brandNewImg.jpg', (err: any) => {
    console.log(err);
  });

}



来源:https://stackoverflow.com/questions/43335490/graphicsmagick-how-to-draw-text-to-fit-a-specific-box-width-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!