Last active
May 23, 2020 17:49
-
-
Save luis-l/6da58b0fa5dad75ba0e99e98f3fa5dec to your computer and use it in GitHub Desktop.
Godot: Fit RichTextLabel to text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends RichTextLabel | |
var width_adjust = 1.4 | |
var default_font = get("custom_fonts/normal_font") | |
# Array of string representing multi-line text. | |
func set_text(lines:Array): | |
clear() | |
for ln in lines: | |
add_text(ln) | |
newline() | |
fit_to_lines(lines) | |
func fit_to_lines(lines:Array): | |
var size = max_extents(lines) | |
size.x *= width_adjust | |
set_size(size) | |
func max_extents(lines:Array): | |
var sizes = line_sizes(lines) | |
var widths = [] | |
var sum_height = 0 | |
for s in sizes: | |
widths.append(s.x) | |
sum_height += s.y | |
return Vector2(widths.max(), sum_height) | |
func line_size(line:String): | |
return default_font.get_string_size(line) | |
func line_sizes(lines:Array): | |
var sizes = [] | |
for ln in lines: | |
sizes.append(line_size(ln)) | |
return size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment