Skip to content

Commit

Permalink
Add first pass font rendering to GL driver
Browse files Browse the repository at this point in the history
This is very inefficient and lacks styles, but shows the concept
  • Loading branch information
andydotxyz committed Nov 19, 2018
1 parent f935c33 commit 0810658
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
29 changes: 29 additions & 0 deletions driver/gl/draw.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"github.com/fyne-io/fyne/canvas"
"github.com/fyne-io/fyne/theme"
"github.com/go-gl/gl/v3.3-core/gl"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
"image/draw"
"log"
"os"
Expand Down Expand Up @@ -224,12 +226,39 @@ func (c *glCanvas) drawImage(img *canvas.Image, pos fyne.Position) {
c.drawRawImage(raw, img.Size, pos)
}

func (c *glCanvas) drawText(text *canvas.Text, pos fyne.Position) {
bounds := text.MinSize()
width := scaleInt(c, bounds.Width)
height := scaleInt(c, bounds.Height)

img := image.NewRGBA(image.Rect(0, 0, width, height))

var opts truetype.Options
font := fontCache()
fontSize := float64(text.TextSize) * float64(c.Scale())
opts.Size = fontSize
face := truetype.NewFace(fontCache(), &opts)

ctx := freetype.NewContext()
ctx.SetDPI(72)
ctx.SetFont(font)
ctx.SetFontSize(fontSize)
ctx.SetClip(img.Bounds())
ctx.SetDst(img)
ctx.SetSrc(&image.Uniform{theme.TextColor()})

ctx.DrawString(text.Text, freetype.Pt(0, height+2-face.Metrics().Descent.Ceil()))
c.drawRawImage(img, bounds, pos)
}

func (c *glCanvas) drawObject(o fyne.CanvasObject, offset fyne.Position) {
pos := o.CurrentPosition().Add(offset)
switch obj := o.(type) {
case *canvas.Rectangle:
c.drawRectangle(obj, pos)
case *canvas.Image:
c.drawImage(obj, pos)
case *canvas.Text:
c.drawText(obj, pos)
}
}
28 changes: 27 additions & 1 deletion driver/gl/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ package gl

import (
"github.com/fyne-io/fyne"
"github.com/fyne-io/fyne/theme"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"log"
)

type gLDriver struct {
Expand All @@ -12,8 +16,30 @@ type gLDriver struct {
done chan interface{}
}

// TODO for styles...
var fontRegular *truetype.Font

func fontCache() *truetype.Font {
if fontRegular != nil {
return fontRegular
}

loaded, err := truetype.Parse(theme.TextFont().Content())
if err != nil {
log.Println("Font error", err)
}
fontRegular = loaded
return fontRegular
}

func (d *gLDriver) RenderedTextSize(text string, size int, style fyne.TextStyle) fyne.Size {
return fyne.NewSize(len(text)*10, size+4)
var opts truetype.Options

opts.Size = float64(size)
face := truetype.NewFace(fontCache(), &opts)
advance := font.MeasureString(face, text)

return fyne.NewSize(advance.Ceil(), face.Metrics().Height.Ceil())
}

func (d *gLDriver) Quit() {
Expand Down

0 comments on commit 0810658

Please sign in to comment.