如何使用tview在Go应用程序中获取屏幕大小(宽度,高度)?

z9zf31ra  于 2024-01-04  发布在  Go
关注(0)|答案(1)|浏览(278)

“我目前正在使用tview库开发一个Go应用程序,用于构建基于终端的用户界面。我需要获取屏幕大小(宽度和高度)以正确配置我的应用程序布局。但是,我在tview库中找不到直接获取屏幕大小的函数。
有没有人可以提供指导,如何获得屏幕尺寸时,使用tview?如果没有在tview直接功能,有没有一个推荐的方法来实现这一点,使用底层tcell包或任何其他方法?”
我试图在tview库中找到一个直接的函数来检索屏幕大小,但我找不到。随后,我探索了tcell包,这是tview使用的底层终端处理库,但我在使用tcell.Screen.Size()获取屏幕大小时遇到了困难。
我的期望是找到一种直接的方法来获取屏幕的宽度和高度,无论是通过tview还是tcell,以正确地配置我的Go应用程序的布局。然而,我目前不确定正确的方法,并希望指导如何实现这一点。

hmtdttj4

hmtdttj41#

假设你使用的是Linux系统:
封装主电路

  1. import (
  2. "github.com/gdamore/tcell"
  3. "os"
  4. "fmt"
  5. )
  6. func main() {
  7. p := GetPrinter()
  8. var st tcell.Style
  9. sty := st.Foreground(tcell.ColorRed).Dim(true)
  10. p.Println("Hello", sty)
  11. a, b := p.Screen.Size()
  12. p.Println(fmt.Sprintf("%v %v", a ,b ), sty)
  13. p.Return()
  14. return
  15. }
  16. type Printer struct {
  17. Screen tcell.Screen
  18. Cursor Coords
  19. DefaultStyle tcell.Style
  20. Size
  21. }
  22. //keep track of our last known screen size
  23. type Size struct {
  24. X int
  25. Y int
  26. }
  27. //x = vertical
  28. //y = horizontal
  29. type Coords struct {
  30. X int
  31. Y int
  32. }
  33. func (p *Printer) Clear() {
  34. p.Screen.Clear()
  35. p.Screen.Show()
  36. }
  37. func (p *Printer) Return() {
  38. p.Cursor.X = 0
  39. p.Cursor.Y++
  40. }
  41. func (p *Printer) CurosorRight() {
  42. p.Cursor.X++
  43. if p.Cursor.X >= p.Size.X {p.Return()}
  44. }
  45. func (p *Printer) CurosorLeft() {
  46. if p.Cursor.X < 1 {return}
  47. p.Cursor.X--
  48. }
  49. func (p *Printer) UpdateSize() {
  50. p.Size.X, p.Size.Y = p.Screen.Size()
  51. }
  52. func (p *Printer) Print(str string, sty tcell.Style) {
  53. //whenever we print, we should update our screen size in case the user has changed it.
  54. p.UpdateSize()
  55. for _, v := range []rune(str) {
  56. p.Screen.SetContent(p.Cursor.X, p.Cursor.Y, v, nil, sty)
  57. p.CurosorRight()
  58. }
  59. p.Screen.Show()
  60. return
  61. }
  62. func (p *Printer) Println(str string, sty tcell.Style) {
  63. //whenever we print, we should update our screen size in case the user has changed it.
  64. p.UpdateSize()
  65. for _, v := range []rune(str) {
  66. p.Screen.SetContent(p.Cursor.X, p.Cursor.Y, v, nil, sty)
  67. p.CurosorRight()
  68. }
  69. p.Return()
  70. p.Screen.Show()
  71. return
  72. }
  73. func GetPrinter() Printer {
  74. s, err := tcell.NewScreen()
  75. if err != nil {fmt.Println(err.Error()); os.Exit(1) }
  76. s.Init()
  77. sty := tcell.StyleDefault.Foreground(tcell.ColorLightGrey).Background(tcell.ColorBlack)
  78. s.SetStyle(sty)
  79. c := Coords{
  80. X: 0,
  81. Y: 0,
  82. }
  83. var p = Printer{
  84. Screen: s,
  85. DefaultStyle: sty,
  86. Cursor: c,
  87. }
  88. return p
  89. }

字符串
这确实有效,如果你调整窗口大小,你会得到不同的结果。我在windows系统上尝试过,似乎也有效,但我不能调整窗口大小来验证这一点。

展开查看全部

相关问题