PT-BR/svgSetSize: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
(Update usage & examples as per GitHub PR #2589)
Line 11: Line 11:
===Argumentos Opcionais===
===Argumentos Opcionais===
{{OptionalArg}}
{{OptionalArg}}
*'''callback:''' Uma função de callback que será chamada na criação do documento XML e na criação de textura (depois de redimensionar), útil para saber se o elemento SVG está carregado.
*'''callback:''' Uma função de retorno de chamada que é armazenada no SVG e disparada toda vez que a textura do SVG é atualizada (por exemplo, via [[svgSetSize]]). Nota: se presente, isso substituirá o retorno de chamada atual armazenado no [[svg]]


===Retornos===
===Retornos===
Line 17: Line 17:


==Exemplo==
==Exemplo==
Esse exmplo cria um elemento [[svg]] (usando função de callback para iniciar o desenho) incluindo um keybind para redimensionar o [[svg]] aleatoriamente (consulte bindKey).
Este exemplo cria um elemento [[svg]] incluindo um keybind (F2) para adicionar um nó rect filho, com o uso de uma função de callback para notificar no debugscript quando o SVG foi atualizado.
 
'''IMPORTANTE''': Dependendo da sua implementação, uma função de callback será necessário para garantir que a textura SVG e o documento XML estejam carregados.


<syntaxhighlight lang="lua">
<syntaxhighlight lang="lua">
-- Isso também pode ser um arquivo, com o diretório do arquivo fornecido no svgCreate
-- Isso também pode ser um arquivo, com o caminho fornecido para svgCreate
local rawSvgData = [[
local rawSvgData = [[
     <svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
     <svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
Line 29: Line 27:
]]
]]


local svg
local svgs = {}


function init()
local function render(svg)
     -- Cria um círculo em SVG, usando os dados, usando os dados brutos XML acima.
     if (not isElement(svg)) or (getElementType(svg) ~= "svg") then
    svg = svgCreate(500, 500, rawSvgData, function(didLoad)
         removeEventHandler("onClientRender", root, svgs[svg].handler)
         if (not didLoad) then -- Se o SVG falhou em carregar, essa função não continuará.
        svgs[svg] = nil
            return
    end
        end


        onSvgLoad(svg)
    local width, height = svgGetSize(svg)
     end)
     dxDrawImage(0, 0, width, height, svg, 0, 0, 0, tocolor(255, 255, 255), false)
end
end
addEventHandler("onClientResourceStart", resourceRoot, init)


local function onUpdate(svg)
    -- Se esta for a primeira atualização, adicione svg à nossa tabela e comece a desenhá-la
    if (not svgs[svg]) then
        svgs[svg] = {
            state = true,
            handler = function()
                render(svg)
            end
        }
        addEventHandler("onClientRender", root, svgs[svg].handler)
    end


-- Implementando a função de callback para carregar o SVG
     iprint("Textura SVG atualizada.", svg, getTickCount())
function onSvgLoad(svg)
     addEventHandler("onClientRender", root, render)
end
end


function render()
local function init()
     local width, height = svgGetSize(svg)
     -- Cria um SVG contendo um círculo, usando os dados XML brutos acima
     dxDrawImage(0, 0, width, height, svg, 0, 0, 0, tocolor(255, 255, 255), false)
     local mySvg = svgCreate(500, 500, rawSvgData, onUpdate)
 
    -- Vincule uma chave para criar um nó filho SVG rect, que acionará o retorno de chamada onUpdate
    bindKey("F2", "down", function()
        addSVGRectNode(mySvg)
    end)
end
end
addEventHandler("onClientResourceStart", resourceRoot, init)


-- Adicionando um keybind para definir um tamanho aleatorio para o SVG
-- Adiciona um nó reto ao SVG com cor, tamanho e posição aleatórios
bindKey("r", "down", function()
function addSVGRectNode(svg)
     if (not isElement(svg)) or (getElementType(svg) ~= "svg") then
    -- Obter o documento XML do nosso SVG
        return false
    local svgXML = svgGetDocumentXML(svg)
    end
   
    -- Adicione um nó SVG reto, posicionado no centro do documento
    local rect = xmlCreateChild(svgXML, "rect")
 
    local size = math.random(0, 50)
     local r, g, b = math.random(10, 99), math.random(10, 99), math.random(10, 99)


     local size = math.random(100, 500)
     xmlNodeSetAttribute(rect, "x", (size / 2) .. "%")
     svgSetSize(svg, size, size)
    xmlNodeSetAttribute(rect, "y", (size / 2) .. "%")
end)
     xmlNodeSetAttribute(rect, "width", size .. "%")
    xmlNodeSetAttribute(rect, "height", size .. "%")
    xmlNodeSetAttribute(rect, "fill", "#" .. r .. g .. b)
   
    -- Aplique nosso XML ao SVG e comece a desenhar via callback
    svgSetDocumentXML(svg, svgXML)
end
</syntaxhighlight>
</syntaxhighlight>



Revision as of 01:39, 9 April 2022

Template:BR/Funcao cliente Define o documento XML subjacente de um elemento SVG.

Sintaxe

bool svgSetSize( svg svgElement, int width, int height [, function callback ( bool didLoad ) ] )

Argumentos Necessários

  • svgElement: O elemento svg que você deseja definir o tamanho.
  • width: Largura, de preferência em potência de dois (16, 32, 64 etc.), o máximo é 4096
  • height : Altura, de preferência em potência de dois (16, 32, 64 etc.), o máximo é 4096

Argumentos Opcionais

NOTE: When using optional arguments, you might need to supply all arguments before the one you wish to use. For more information on optional arguments, see optional arguments.

  • callback: Uma função de retorno de chamada que é armazenada no SVG e disparada toda vez que a textura do SVG é atualizada (por exemplo, via svgSetSize). Nota: se presente, isso substituirá o retorno de chamada atual armazenado no svg

Retornos

  • Retorna true se for bem sucedido, false caso dê errado.

Exemplo

Este exemplo cria um elemento svg incluindo um keybind (F2) para adicionar um nó rect filho, com o uso de uma função de callback para notificar no debugscript quando o SVG foi atualizado.

-- Isso também pode ser um arquivo, com o caminho fornecido para svgCreate
local rawSvgData = [[
    <svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
        <circle cx="250" cy="250" r="250" fill="#0fc0fc" />
    </svg>
]]

local svgs = {}

local function render(svg)
    if (not isElement(svg)) or (getElementType(svg) ~= "svg") then
        removeEventHandler("onClientRender", root, svgs[svg].handler)
        svgs[svg] = nil
    end

    local width, height = svgGetSize(svg)
    dxDrawImage(0, 0, width, height, svg, 0, 0, 0, tocolor(255, 255, 255), false)
end

local function onUpdate(svg)
    -- Se esta for a primeira atualização, adicione svg à nossa tabela e comece a desenhá-la
    if (not svgs[svg]) then
        svgs[svg] = {
            state = true,
            handler = function()
                render(svg)
            end
        }

        addEventHandler("onClientRender", root, svgs[svg].handler)
    end

    iprint("Textura SVG atualizada.", svg, getTickCount())
end

local function init()
    -- Cria um SVG contendo um círculo, usando os dados XML brutos acima
    local mySvg = svgCreate(500, 500, rawSvgData, onUpdate)

    -- Vincule uma chave para criar um nó filho SVG rect, que acionará o retorno de chamada onUpdate
    bindKey("F2", "down", function()
        addSVGRectNode(mySvg)
    end)
end
addEventHandler("onClientResourceStart", resourceRoot, init)

-- Adiciona um nó reto ao SVG com cor, tamanho e posição aleatórios
function addSVGRectNode(svg)
    -- Obter o documento XML do nosso SVG
    local svgXML = svgGetDocumentXML(svg)
    
    -- Adicione um nó SVG reto, posicionado no centro do documento
    local rect = xmlCreateChild(svgXML, "rect")

    local size = math.random(0, 50)
    local r, g, b = math.random(10, 99), math.random(10, 99), math.random(10, 99)

    xmlNodeSetAttribute(rect, "x", (size / 2) .. "%")
    xmlNodeSetAttribute(rect, "y", (size / 2) .. "%")
    xmlNodeSetAttribute(rect, "width", size .. "%")
    xmlNodeSetAttribute(rect, "height", size .. "%")
    xmlNodeSetAttribute(rect, "fill", "#" .. r .. g .. b)
    
    -- Aplique nosso XML ao SVG e comece a desenhar via callback
    svgSetDocumentXML(svg, svgXML)
end

Requisitos

Minimum server version n/a
Minimum client version 1.5.8-9.20979

Note: Using this feature requires the resource to have the above minimum version declared in the meta.xml <min_mta_version> section. e.g. <min_mta_version client="1.5.8-9.20979" />

Veja também