Auto-Sizing Text Windows
by RPG Advocate
saved from Phylomortis.Com
Introduction
This script adds the ability to show text windows whose dimensions conform to the text inside them. The width of the window is determined by the width of the longest line. The height is determined by the number of lines. To use this script, just add the Window_Autosize class provided after all the other window classes. The way the text box is a bit cumbersome. You initialize the window with an array of lines. The class does the processing from there. Please don't initialize the window with an empty array. This will cause the game to show an error message, as shown in the script. Also, be aware that the initial x and y coordinate of 0 are just dummy values. To use this script effectively, you should either specify explicit x and y coordinates for the window or create an algorithm to determine them, if you need to display the window in a different location depending on the circumstances.
Script
AutoSizing Text Windows
Code:
# Auto-Sizing Text Windows
# by RPG Advocate
#==============================================================================
# ** Window_Autosize
#------------------------------------------------------------------------------
# This message window autosizes to suit the text displayed.
#==============================================================================
class Window_Autosize < Window_Base
#--------------------------------------------------------------------------
# * Object Initialization
# lines : lines
#--------------------------------------------------------------------------
def initialize(lines)
@lines = []
@lines = lines
@line_width = []
if @lines.size == 0
print("Error: Auto-sizing windows must have at least one line")
exit
end
@tester = Window_Base.new(0, 0, 640, 480)
@tester.contents = Bitmap.new(@tester.width - 32, @tester.height - 32)
@tester.contents.font.name = "Arial"
@tester.contents.font.size = 18
max = 0
for i in 0..@lines.size - 1
t = @lines[i]
@line_width[i] = @tester.contents.text_size(t).width
if @line_width[i] > max
max = @line_width[i]
end
end
w = max + 40
h = @lines.size + 1
h *= 32
@tester.dispose
super(0, 0, w, h)
self.contents = Bitmap.new(width - 32, height - 32)
self.contents.font.name = "Arial"
self.contents.font.size = 18
refresh
end
#--------------------------------------------------------------------------
# * Refresh
#--------------------------------------------------------------------------
def refresh
self.contents.clear
self.contents.font.color = normal_color
self.opacity = 255
self.back_opacity = 255
self.contents_opacity = 255
for i in 0..@lines.size - 1
t = @lines[i]
self.contents.draw_text(4, i*32, @line_width[i], 32, t)
end
end
#--------------------------------------------------------------------------
# * Frame Update
#--------------------------------------------------------------------------
def update
super
end
end