TextService

Show Deprecated
Not Creatable
Service
Not Replicated

The TextService is a service internally responsible for handling the display of text in the game.

This class has two member functions:

The TextService:GetTextSize() function gives developers the ability to calculate the space required for a specific text string with specified formatting, returning a Vector2 pixel size.

The TextService:FilterStringAsync() function is required to properly filter user specified text (such as chat messages or other inputs) in the interests of user safety. Developers not using the Roblox default Chat, or allowing users to otherwise input text must use this function.

Summary

Properties

Events

Methods

GetTextSize(string: string, fontSize: number, font: Font, frameSize: Vector2): Vector2  

Computes the Vector2 dimensions (in pixels) that will be taken up with text when using the specified formatting parameters and size constraints.

SetResolutionScale(scale: number): void  


FilterStringAsync(stringToFilter: string, fromUserId: number, textContext: TextFilterContext): Instance  YIELDS

Filters a string being received from a user, and returns a TextFilterResult which can be used to distribute the correctly filtered text accordingly.

GetFamilyInfoAsync(assetId: Content): table  YIELDS

Returns a table containing the name and faces of a font family.


Calculates the width and height of text given parameters.

Properties

Events

Methods

GetFontMemoryData

Roblox Script Security

Returns

GetTextSize

Computes the Vector2 dimensions (in pixels) that will be taken up with text when using the specified formatting parameters and size constraints.

Note, the fontSize parameter will not accept the FontSize Enum. Instead the integer size corresponding with the FontSize Enum should be used. This is not equal to the value of the FontSize Enum. For example, for Size11 font, the integer 11 should be used.

This function is a useful alternative to the TextLabel.TextBounds property of the TextLabel and TextButton objects. Using the TextLabel.TextBounds property to calculate the dimensions text requires is often impractical as it requires a TextLabel object to be created.

With GetTextSize, the dimensions required by a particular text string in a particular TextLabel or TextButton can be calculated before any object is created or text property set.

Developers are recommended to add a pixel of padding to the result to ensure no text is cut off.

This method is limited to only fonts that are listed in Font. To get access to more fonts, you can use TextService:GetTextBoundsAsync() instead.

Parameters

string: string

The string for which the text size is to be calculated.

fontSize: number

The integer representing the font size used.

font: Font

The font used.

frameSize: Vector2

The TextLabel.AbsoluteSize of the text object to be used. Required to compute how the text will wrap.


Returns

The size of the space required, in pixels, by the string with the specified formatting.

Code Samples

TextService: Getting the Text Size

1local TextService = game:GetService("TextService")
2
3local function getTextBounds()
4 local message = "Hello World"
5 local size = Vector2.new(1, 1)
6 local bounds = TextService:GetTextSize(message, 12, "SourceSans", size)
7 return bounds + Vector2.new(1, 1)
8end
9
10print(getTextBounds())

SetResolutionScale

void
Roblox Script Security

Parameters

scale: number

Returns

void

FilterStringAsync

Yields

The FilterStringAsync function filters a string being received from a user, using the TextService, and returns a TextFilterResult which can be used to distribute the correctly filtered text accordingly.

Usage

This method should be called once each time a user submits a message. Do not cache the results of this function and re-use them for separate messages. If a user submits the same text multiple times this method must be called again each time the message is sent. If the results are cached and reused spam detection and many forms of context-aware filtering will be broken and potentially put user safety at risk. Games that improperly use cached results may face moderation.

However, it is encouraged to keep these result objects to display the same message to users who join the server later. For example: this can be used to safely and efficiently implement a server chat log that always uses the least restrictive filtering for users who join later, or for efficiently displaying text like a pet name to a user who joins the game after the pet was first spawned and name filtered.

The optional TextFilterContext parameter will not impact the filtered result of the query. This value will be used to improve Roblox's text filtering.

Private text is anything that is seen only by specific players, rather than every player. For example, if the chat is seen by a single player, or by a selected group of players, then the chat is considered private. Chat for teams or chat that is potentially visible to a wider group, such as the server, is considered public. If you are unsure what your text qualifies as, leave the optional field blank.

Note:

  • This method always yields to make a text filtering service call
  • This method may throw if there is a service error that can not be resolved. If this function throws an error please do not retry the request; this method implements it's own retry logic internally. If this method fails do not display the text to any user.
  • This method currently throws if fromUserId is not online on the current server. We plan to support users who are offline or on a different server in the future.

Parameters

stringToFilter: string

The text to be filtered.

fromUserId: number

The userId of the player filtering the text.

textContext: TextFilterContext

The context that the filtered message will be used in. The default is PrivateChat.

Default Value: "PrivateChat"

Returns

Code Samples

Pet Name Filter Example

1local ReplicatedStorage = game:GetService("ReplicatedStorage")
2local TextService = game:GetService("TextService")
3local Players = game:GetService("Players")
4
5local Remotes = Instance.new("Folder")
6Remotes.Name = "PetNamingRemotes"
7Remotes.Parent = ReplicatedStorage
8
9local UserNamedPet = Instance.new("RemoteEvent")
10UserNamedPet.Name = "UserNamedPet"
11UserNamedPet.Parent = Remotes
12
13local SendPetName = Instance.new("RemoteEvent")
14SendPetName.Name = "SendPetName"
15SendPetName.Parent = Remotes
16
17local RequestAllPetNames = Instance.new("RemoteFunction")
18RequestAllPetNames.Name = "RequestAllPetNames"
19RequestAllPetNames.Parent = Remotes
20
21local filterResults = {}
22
23local function broadcastPetName(userId)
24 local filterResult = filterResults[userId]
25 if filterResult then
26 for _, player in pairs(Players:GetPlayers()) do
27 if player then
28 -- spawn a new thread so as to not yield the update
29 task.spawn(function()
30 -- grab the filtered string for this user
31 local toUserId = player.UserId
32 local filteredString = filterResult:GetNonChatStringForUserAsync(toUserId)
33 filteredString = filteredString or ""
34 SendPetName:FireClient(player, userId, filteredString)
35 end)
36 end
37 end
38 end
39end
40
41UserNamedPet.OnServerEvent:Connect(function(player, petName)
42 local fromUserId = player.UserId
43
44 -- pcall to catch errors
45 local success, result = pcall(function()
46 return TextService:FilterStringAsync(petName, fromUserId)
47 end)
48
49 if success then
50 filterResults[fromUserId] = result
51 broadcastPetName(fromUserId)
52 else
53 print("Could not filter pet name")
54 end
55end)
56
57RequestAllPetNames.OnServerInvoke = function(player)
58 local toUserId = player.UserId
59
60 local petNames = {}
61
62 -- go through filter results and filter the pet name to be sent
63 for fromUserId, filterResult in pairs(filterResults) do
64 local filteredString = filterResult:GetNonChatStringForUserAsync(toUserId)
65 filteredString = filteredString or ""
66
67 -- need to convert userId to string so it can't be sent via a remote function
68 petNames[tostring(fromUserId)] = filteredString
69 end
70
71 return petNames
72end
73
74Players.PlayerRemoving:Connect(function(oldPlayer)
75 local userId = oldPlayer.UserId
76 filterResults[userId] = nil
77end)

GetFamilyInfoAsync

Yields

Returns a table containing the name and faces of a font family.

The returned table is structured like this:


1type FaceInfo = {
2 Name: string, -- Examples: "Regular", "Book", "Italic", "Thin Italic"
3 Weight: Enum.FontWeight,
4 Style: Enum.FontStyle, -- Either Normal or Italic
5}
6
7type FamilyInfo = {
8 Name: string, -- Examples: "Source Sans Pro", "Grenze Gotisch"
9 Faces: {FaceInfo} -- There's always at least 1 but there can be up to 18.
10}
11

If the font family has already been loaded by a previous call to GetFamilyInfoAsync, ContentProvider:PreloadAsync(), or a text object with the TextLabel.FontFace property set, then the method returns without yielding.

Errors

This method can fail because of network errors. You should always wrap it in a pcall for error handling.

Throws an error in these scenarios:

  • The passed family is an empty string.
  • Downloading the family failed.
  • The asset ID is invalid or points to an asset that doesn't exist.

Parameters

assetId: Content

Asset ID of the font family to look up.


Returns

The information about the font family.

Code Samples

TextService: Getting font family information

1local TextService = game:GetService("TextService")
2
3local familyToCheck = "rbxasset://fonts/families/Arial.json"
4
5-- This is a yield function which may take up to a few seconds to download the font.
6local info = TextService:GetFamilyInfoAsync(familyToCheck)
7
8print("Name of the font:", info.Name)
9print("Faces:")
10for _, face in info.Faces do
11 print("--------")
12 print("Name:", face.Name)
13 print("Weight:", face.Weight.Name)
14 print("Style:", face.Style.Name)
15end

GetTextBoundsAsync

Yields

This method is similar to TextService:GetTextSize(), but uses the Font object instead of Font, which has access to more fonts.

Used to measure how big some text will be given a set of properties like the string, size, and font.

This is a yield function because some fonts may need to be loaded in order to measure them. If the font is already loaded, then it will not yield. ContentProvider:PreloadAsync() can be used to make sure a font is loaded.

Errors

This method can fail because of network errors. You should always wrap it in a pcall for error handling.

Throws an error in these scenarios:

  • The GetTextBoundsParams.Font has a blank family.
  • The params argument was nil.
  • The font family or font face failed to download.

Parameters

A reference to a GetTextBoundsParams object.


Returns

The size of the text as a Vector2.

Code Samples

TextService: Measuring text size

1local TextService = game:GetService("TextService")
2
3local params = Instance.new("GetTextBoundsParams")
4params.Text = "hello world!"
5params.Font = Font.new("rbxasset://fonts/families/GrenzeGotisch.json", Enum.FontWeight.Thin)
6params.Size = 20
7params.Width = 200
8local size = TextService:GetTextBoundsAsync(params)
9
10print("The size of the text is:", size)