简体   繁体   中英

How do I measure the bounds of a string in wand?

I'm using Wand to generate a JPG with custom variable text inside it. I have an array of strings all with the same width but different heights. Is there a method to word wrap a long text inside a boundary or calculate the height needed for the text so when drawing the texts from the array they don't overlap.

with Drawing() as ctx:
        with Image(width=1080, height=1080, background=Color("WHITE")) as img:
            with Drawing() as draw: 
                for i,line in enumerate(lines):
                     metrics = draw.get_font_metrics(img, line, multiline=True)
                     draw.text(x=150, y=120+(i*35)+int(metrics.text_height), body=line)
                draw(img)
                img.sample(1080, 1080)
                img.save(filename="output.png")

This may not be the answer(s) your looking for, but will hopefully get you on the right path.

How do I measure the bounds of a string in wand?

Your already doing it. Rather than a "smart-n-quick" one-liner approach, I would suggest a more classic offset & accumulator approach to map positions that update with each iteration.

top_margin = 120
line_offset = 0
line_padding = 35
with Drawing() as ctx:
    with Image(width=1080, height=1080, background=Color("WHITE")) as img:
        with Drawing() as draw: 
            for i,line in enumerate(lines):
                metrics = draw.get_font_metrics(img, line, multiline=True)
                draw.text(x=150, y=y=top_margin + line_offset, body=line)
                line_offset += int(metrics.text_height) + line_padding

Is there a method to word wrap a long text inside a boundary or calculate the height needed for the text so when drawing the texts from the array they don't overlap.

The short answer is no . You would be responsible for implementing the algorithm. Luckily the internet is full of examples & research articles that can be referenced. It can be as basic as find-the-last-space-before-overflow...

lines = [
    'I\'m using Wand to generate a JPG with custom variable text inside it.',
    'I have an array of strings all with the same width but different heights',
    'Is there a method to word wrap a long text inside a boundary or calculate the height needed for the text so when drawing the texts from the array they don\'t overlap',
]
image_width = 540
image_height = 540
left_margin = 150
right_margin = image_width - left_margin * 2
top_margin = 120
line_padding = 35
line_offset = 0
with Drawing() as ctx:
    with Image(width=image_width, height=image_height, background=Color("LIGHTCYAN")) as img:
        with Drawing() as draw: 
            for i,line in enumerate(lines):
                metrics = draw.get_font_metrics(img, line, multiline=True)
                last_idx = 1
                # Do we need to do work?
                while metrics.text_width > right_margin:
                    last_breakpoint=0
                    # Scan text for possible breakpoints.
                    for idx in range(last_idx, len(line)):
                        if line[idx] == ' ':
                            last_breakpoint = idx
                        else:
                            # Determine if we need to insert a breakpoint.
                            metrics = draw.get_font_metrics(img, line[:idx], multiline=True)
                            if metrics.text_width >= right_margin:
                                line = line[:last_breakpoint].strip() + '\n' + line[last_breakpoint:].strip()
                                last_idx = last_breakpoint
                                break
                    # Double check any modifications to text was successful enough.
                    metrics = draw.get_font_metrics(img, line, multiline=True)
                draw.text(x=left_margin, y=top_margin + line_offset, body=line)
                line_offset += int(metrics.text_height) + line_padding
            draw(img)
            img.save(filename="output.png")

产量

The above code could be optimized, and Python might already include some better methods .

Further reading...

The source code ImageMagick's CAPTION: protocol is a good example. The algorithm repeatedly calls GetMultilineTypeMetrics as well as FormatMagickCaption to adjust pointsize & insert line-breaks. The wand library doesn't really support the caption protocol, but you can play-around with it by using the following workaround.

from wand.api import library
# ...
with Image(width=image_width, height=image_height, background=Color("LIGHTCYAN")) as img:
    for i,line in enumerate(lines):
        # Create a tempory image for each bounding box
        with Image() as throwaway:
            library.MagickSetSize(throwaway.wand, right_margin, line_padding)
            throwaway.read(filename='CAPTION:'+line)
            img.composite(throwaway, left_margin, top_margin + line_offset)
            line_offset += line_padding + throwaway.height
    img.save(filename="output.png")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM