fogleman / gg

Go Graphics - 2D rendering in Go with a simple API.
https://godoc.org/github.com/fogleman/gg
MIT License
4.37k stars 354 forks source link

How would I create a context that just fits the text? #105

Closed DiegoMagdaleno closed 4 years ago

DiegoMagdaleno commented 4 years ago

Hi! First of all thanks for your amazing work, im kind of new to Golang, and im working on a "meme" generator that basically puts a dog in top of a desired image, I finished that part.

But I want to add text, so far the library has been very pleasing to use, the problem is that it generates lets say, a square when I only want the text.

Here is an example:

Have:

Screen Shot 2020-07-17 at 3 48 21 PM

Want:

Screen Shot 2020-07-17 at 3 48 42 PM

The code is very similar to the one used in the meme example:

package lib

import (
    "log"
    "strconv"
    "strings"

    "github.com/fogleman/gg"
)

func CreateText(text, textDimentions, savePath string) {
    splitDimentions := strings.Split(textDimentions, "x")
    dimenX, err := strconv.Atoi(splitDimentions[0])
    if err != nil {
        log.Panic("Error while parsing the text dimentions to int")
    }
    dimenY, err := strconv.Atoi(splitDimentions[1])
    if err != nil {
        log.Panic("Error while parsing the text dimentions to int")
    }
    imageSession := gg.NewContext(dimenX, dimenY)
    imageSession.SetRGBA(0, 0, 0, 0)
    imageSession.Clear()
    fontHeight := calculateFontHeight(dimenX, dimenY)
    fontLocation := whereIsTheFont()
    if err = imageSession.LoadFontFace(fontLocation, fontHeight); err != nil {
        log.Panic("Error while loading fontface, is the font face installed?")
    }
    imageSession.SetRGB(0, 0, 0)
    stroke := 4
    for imageSessionY := -stroke; imageSessionY <= stroke; imageSessionY++ {
        for imageSessionX := -stroke; imageSessionX <= stroke; imageSessionX++ {
            if imageSessionX*imageSessionX+imageSessionY*imageSessionY >= stroke*stroke {
                continue
            }
            x := float64(dimenX/2) + float64(imageSessionX)
            y := float64(dimenY/2) + float64(imageSessionY)
            imageSession.DrawStringAnchored(text, x, y, 0.5, 0.5)
        }
    }
    imageSession.SetRGB(1, 1, 1)
    imageSession.DrawStringAnchored(text, float64(dimenX/2), float64(dimenY/2), 0.5, 0.5)
    imageSession.SavePNG(savePath)
}

So my only question is, is there any way I could just have the text, aka, the context should fix the text, so it is only the transparent "hey".

Thanks a lot!