< Previous | Contents | Next >
Function Creation - Text Rendering
Fuses can have defined Functions that can be called from the other main Process function, These need to be defined before Process, so it knows to reference this function as there is no header file.
This code will Render Text to an image using the shape rendering functions built into the Fusion engine core. See the next section for further explanation.
function drawstring(img, font, style, size, justify, quality, x, y, colour, text)
local ic = ImageChannel(img, quality) local fs = FillStyle()
local cs = ChannelStyle()
cs.Color = colour ic:SetStyleFill(fs)
-- get the fonts metrics
local font = TextStyleFont(font, style) local tfm = TextStyleFontMetrics(font)
-- This is the distance between this line and the next one. local line_height=(tfm.TextAscent + tfm.TextDescent + tfm.
TextExternalLeading) *10 * size local x_move = 0
local mat = Matrix4()
mat:Scale(1.0/tfm.Scale, 1.0/tfm.Scale, 1.0)
mat:Scale(size, size, 1)
-- set the initial baseline position of the text cursor local sh, ch, prevch
local shape = Shape() mat:Move(x, y, 0)
-- split the text into separate lines for line in string.gmatch(text, "%C+") do
-- First pass, work out what the total width of this line is going to be
local line_width = 0 for i=1,#line do
ch = line:sub(i,i):byte()
-- is this ignoring kerning?
line_width = line_width + tfm:CharacterWidth(ch)*10*size
end
-- Now work out our initial cursor position, based on the justification
-- 0 = left justify,
-- 1 = centered
-- 2 = right justify if justify == 0 then
--mat:Move(0, 0, 0) elseif justify == 1 then
mat:Move(-line_width/2, 0, 0) elseif justify == 2 then
mat:Move(-line_width, 0, 0)
end
-- Second pass, now we assemble the actual shape for i=1,#line do
prevch = ch
-- get the character, or glyph ch = line:sub(i,i):byte()
-- first we want to know what the width of the character is,
-- so we know where to start drawing this next character
-- not really sure why we multiply this by 10, we just do :-) local cw = tfm:CharacterWidth(ch)*10*size
-- if there is a previous character, we need to get the kerning
-- between the current character and the last one. if prevch then
x_offset = tfm:CharacterKerning(prevch, ch)*10*size x_move = x_move + x_offset
mat:Move(x_offset, 0, 0)
end
-- move the cursor to the center of the character mat:Move(cw/2, 0, 0)
-- I think this renders the shape we are interested in sh = tfm:GetCharacterShape(ch, false)
sh = sh:TransformOfShape(mat)
-- move the text cursor to the end of the glyph. mat:Move(cw/2, 0, 0)
x_move = x_move + cw
shape:AddShape(sh)
end
