Vamos continuar nosso treinamento e acrescentar alguma funcionalidade ao nosso script.
In the previous lesson, we created an empty function and registered it with GIMP. In this lesson, we want to provide functionality to our script — we want to create a new image, add the user's text to it and resize the image to fit the text exactly.
Once you know how to set variables, define functions and access list members, the rest is all downhill — all you need to do is familiarize yourself with the functions available in GIMP's procedural database and call those functions directly. Open the Seção 12.9, “O navegador de procedimentos”.
Vamos começar criando uma nova imagem. vamos criar uma nova variável com o nome theImage
, e atribuir a ela o resultado de chamar a função do GIMP gimp-image-new
.
As you can see from the DB Browser, the function
gimp-image-new
takes three parameters — the
image's width, height and the type of image. Because we'll
later resize the image to fit the text, we'll make a 10×10 pixels
RGB
image. We'll store the image's width and sizes in some
variables, too, as we'll refer to and manipulate them later in
the script.
(define (script-fu-text-box inText inFont inFontSize inTextColor) (let* ( ; definir nossas variáeis locais (theImageWidth 10) (theImageHeight 10) ; criar uma nova imagem: (theImage (car (gimp-image-new theImageWidth theImageHeight RGB ) ) ) (theText) ;uma declaração para o textot ;que vamos criar depois
Nota: nós usamos o valor RGB
para especificar que a imagem é uma imagem RGB . Nós também poderíamos ter usado o valor 0
, mas RGB é mais descritivo quando nós (e outras pessoas, quando publicarmos o script na internet), formos olhar o código de volta.
You should also notice that we took the head of the result of the function call. This may seem strange, because the database explicitly tells us that it returns only one value — the ID of the newly created image. However, all GIMP functions return a list, even if there is only one element in the list, so we need to get the head of the list.
Agora que temos uma imagem, precisamos adicionar uma camada à mesma. Nós podemos chamar a função gimp-layer-new
para criar a nova camada, passando a referência (ID) da imagem que acabamos de criar. (Daqui por diante, em vez de listar a função toda, mostraremos só as linhas que estamos adicionando à mesma. Você pode ver o script completo aqui).
;create a new layer for the image: (theLayer (car (gimp-layer-new theImage "layer 1" theImageWidth theImageHeight RGB-IMAGE 100 LAYER-MODE-NORMAL ) ) ) ) ;end of our local variables
Uma vez que tenhamos uma nova camada, precisamos adiciona-la a imagem:
(gimp-image-insert-layer theImage theLayer 0 0)
Agora, só por diversão, vamos verificar o resultado de nosso trabalho até esse ponto, e adicionar esta linha para exibir a nova imagem, ainda vazia:
(gimp-display-new theImage)
Save your work, restart GIMP, run the script and a new image should pop up. It will probably contain garbage (random colors), because we haven't erased it. We'll get to that in a second.
Vá em frente, e remova a linha para exibir a imagem (ou comente-a colocando um (;
) no começo da linha)
Antes de adicionar texto a imagem, precisamos configurar a cor de frente e a cor de fundo, de forma que o texto apareça na cor que o usuário especificou. Vamos usar as funções gimp-context-set-back/foreground:
(gimp-context-set-background '(255 255 255) ) (gimp-context-set-foreground inTextColor)
Com as cores selecionadas, vamos limpar o lixo que existe na imagem preenchendo nossa camada com a cor de fundo:
(gimp-drawable-fill theLayer FILL-BACKGROUND)
Com a imagem limpa, podemos começar a adicionar algum texto
(set! theText (car (gimp-text-font theImage theLayer 0 0 inText 0 TRUE inFontSize inFont) ) )
Embora seja uma chamada de função longa, com muitos parâmetros, não há nenhuma surpresa se você olhar os parâmetros e compara-los com os que estão listados na entrada para essa função no navegador de procedimentos. Basicamente, estamos criando uma nova camada de texto, e atribuindo a mesma à variável theText
.
Agora que temos o texto, podemos saber sua largura e sua altura, e redimensionar a imagem e sua camada para o tamanho do texto:
(set! theImageWidth (car (gimp-drawable-get-width theText) ) ) (set! theImageHeight (car (gimp-drawable-get-height theText) ) ) (gimp-image-resize theImage theImageWidth theImageHeight 0 0) (gimp-layer-resize theLayer theImageWidth theImageHeight 0 0)
Se você é como eu, provavelmente está se perguntando o que é um desenhável (drawable) e como é diferente de uma camada (layer). A diferença entre os dois é que um desenhável é qualquer coisa em que se pode desenhar, incluindo camadas, mas isso também inclui canais, máscaras de camada, a seleção, etc...; Uma camada é uma versão mais específica de um desenhável. Na maioria dos casos a distinção não é importante.
Com a imagem pronta para ser exibida, podemos acrescentar de volta nossa linha que diz pra imagem ser exibida em uma janela:
(gimp-display-new theImage)
Save your work, restart GIMP and give your first script a run!
If you try to close the image created without first saving the file, GIMP will ask you if you want to save your work before you close the image. It asks this because the image is marked as dirty, or unsaved. In the case of our script, this is a nuisance for the times when we simply give it a test run and don't add or change anything in the resulting image — that is, our work is easily reproducible in such a simple script, so it makes sense to get rid of this dirty flag.
Para fazer isso, nós limpamos o marcador de sujeira (dirty flag), depois de mostrar a imagem na tela:
(gimp-image-clean-all theImage)
Isso colocará o contador de sujeira em 0, fazendo a imagem parecer estar “limpa”.
Adicionar ou não essa linha é uma questão de gosto pessoal. Eu a uso em scripts que produzem novas imagens, quando os resultados são triviais, como neste caso. Se o seu script for muito complicado, ou se trabalha modificando uma imagem já existente, é melhor não usar essa função.