From 0aff1408842a8e19292a4f07b57ed48c6de0c162 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Mon, 23 Oct 2017 11:18:48 +0200 Subject: [PATCH] Added text width function for font --- allegro5/font.go | 67 ++++++++++++++++++++++++++---------------------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/allegro5/font.go b/allegro5/font.go index d63460c..3a88174 100644 --- a/allegro5/font.go +++ b/allegro5/font.go @@ -6,53 +6,60 @@ package allegro5 import "C" import ( - "fmt" - "unsafe" + "fmt" + "unsafe" ) type Font struct { - font *C.ALLEGRO_FONT + font *C.ALLEGRO_FONT } type HorizontalAlignment int const ( - AlignLeft HorizontalAlignment = iota - AlignCenter - AlignRight + AlignLeft HorizontalAlignment = iota + AlignCenter + AlignRight ) func LoadTTFFont(path string, size int) (*Font, error) { - 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 + 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 { - 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 + 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) { - 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) + 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() { - C.al_destroy_font(f.font) -} \ No newline at end of file + C.al_destroy_font(f.font) +}