zntg/allegro5/font.go

66 lines
1.3 KiB
Go
Raw Normal View History

package allegro5
// #include <allegro5/allegro.h>
// #include <allegro5/allegro_font.h>
// #include <allegro5/allegro_ttf.h>
import "C"
import (
2017-10-23 09:18:48 +00:00
"fmt"
"unsafe"
)
type Font struct {
2017-10-23 09:18:48 +00:00
font *C.ALLEGRO_FONT
}
type HorizontalAlignment int
const (
2017-10-23 09:18:48 +00:00
AlignLeft HorizontalAlignment = iota
AlignCenter
AlignRight
)
func LoadTTFFont(path string, size int) (*Font, error) {
2017-10-23 09:18:48 +00:00
p := C.CString(path)
defer C.free(unsafe.Pointer(p))
f := C.al_load_ttf_font(p, C.int(size), 0)
if nil == f {
return nil, fmt.Errorf("Unable to load TTF font '%s'", path)
}
return &Font{f}, nil
}
func (f *Font) drawFlags(a HorizontalAlignment) C.int {
2017-10-23 09:18:48 +00:00
switch a {
case AlignLeft:
return C.ALLEGRO_ALIGN_LEFT
case AlignCenter:
return C.ALLEGRO_ALIGN_CENTRE
case AlignRight:
return C.ALLEGRO_ALIGN_RIGHT
}
return C.ALLEGRO_ALIGN_LEFT
}
func (f *Font) Draw(left, top float32, color Color, align HorizontalAlignment, text string) {
2017-10-23 09:18:48 +00:00
t := C.CString(text)
defer C.free(unsafe.Pointer(t))
flags := f.drawFlags(align)
C.al_draw_text(f.font, color.color, C.float(left), C.float(top), flags, t)
}
func (f *Font) TextWidth(text string) float32 {
t := C.CString(text)
defer C.free(unsafe.Pointer(t))
return float32(C.al_get_text_width(f.font, t))
}
func (f *Font) Destroy() {
2017-10-23 09:18:48 +00:00
C.al_destroy_font(f.font)
}