code.witches.io/go/sdl2@v0.1.1/ttf/ttf.go (about)

     1  package ttf
     2  
     3  // #cgo windows LDFLAGS: -lSDL2_ttf -lSDL2
     4  // #cgo linux freebsd darwin pkg-config: SDL2_ttf
     5  // #include <SDL2/SDL_ttf.h>
     6  import "C"
     7  import (
     8  	"fmt"
     9  	"unsafe"
    10  
    11  	"code.witches.io/go/sdl2"
    12  )
    13  
    14  type Destroyable interface {
    15  	Destroy()
    16  }
    17  
    18  type Font C.struct_TTF_Font
    19  
    20  func Init() error {
    21  	if C.TTF_Init() == -1 {
    22  		return GetError()
    23  	}
    24  	return nil
    25  }
    26  
    27  func WasInit() bool {
    28  	result := C.TTF_WasInit()
    29  	if result == 0 {
    30  		return false
    31  	}
    32  	return true
    33  }
    34  
    35  func Quit() {
    36  	C.TTF_Quit()
    37  }
    38  
    39  func OpenFont(file string, size int) (*Font, error) {
    40  	nativeFile := C.CString(file)
    41  	defer C.free(unsafe.Pointer(nativeFile))
    42  
    43  	font := (*Font)(C.TTF_OpenFont(nativeFile, C.int(size)))
    44  	if font == nil {
    45  		return nil, GetError()
    46  	}
    47  
    48  	return font, nil
    49  }
    50  
    51  func OpenFontRW(src *sdl.RWOps, freeSrc bool, size int) (*Font, error) {
    52  	var free int
    53  
    54  	if freeSrc {
    55  		free = 1
    56  	}
    57  
    58  	font := (*Font)(C.TTF_OpenFontRW((*C.struct_SDL_RWops)(unsafe.Pointer(src)), C.int(free), C.int(size)))
    59  	if font == nil {
    60  		return nil, GetError()
    61  	}
    62  
    63  	return font, nil
    64  }
    65  
    66  func OpenFontIndex(file string, size int, index int) (*Font, error) {
    67  	nativeFile := C.CString(file)
    68  	defer C.free(unsafe.Pointer(nativeFile))
    69  
    70  	font := (*Font)(C.TTF_OpenFontIndex(nativeFile, C.int(size), C.long(index)))
    71  	if font == nil {
    72  		return nil, GetError()
    73  	}
    74  
    75  	return font, nil
    76  }
    77  
    78  func GetError() error {
    79  	ptr := C.TTF_GetError()
    80  	if ptr == nil {
    81  		return nil
    82  	}
    83  	err := C.GoString(ptr)
    84  	if len(err) == 0 {
    85  		return nil
    86  	}
    87  	return fmt.Errorf("ttf: %s", err)
    88  }
    89  
    90  func (f *Font) Close() {
    91  	C.TTF_CloseFont((*C.struct__TTF_Font)(f))
    92  }