Converta uma imagem de texto em texto “editável”

 

O mundo digital, a cada dia que passa, ocupa mais espaço nas nossas vidas. Exemplo disso é a forma de lidarmos com os documentos que nos servem em muitos serviços e até na nossa profissão. A forma tradicional de lidarmos com esses documentos está paulatinamente a perder terreno. Um texto numa folha de papel é hoje um entrave para muita gente, tendo em conta que enviar um fax – que em tempos atalhava os processos burocráticos – está em desuso e pode dificultar mesmo os serviços administrativos. É a era digital que nos obriga a usar a web e o mail como principais meios de comunicação.

Mas então o que fazemos às resmas de papel que ainda circulam na nossa mesa de trabalho?

 

A ideia é digitalizar… ou melhor, “fotografar” e converter o texto do papel em texto “editável”. Podemos para isso usar um OCR.

OCR – Reconhecimento Óptico de Caracteres

A técnica de reconhecimento de caracteres facilita o transporte do texto e das imagens do papel para o editor de texto. Existem várias aplicações que podemos usar, falei aqui numa aplicação extraordinária, para este serviço, o Abbyy FineReader. Mas é pago e bem pago… no entanto vale cada euro gasto.

Claro que nem todos precisam de uma ferramentas destas todos os dias. Existem aplicações gratuitas e existem serviços onde podemos fazer esta conversão.

Hoje deixo-vos três interessantes serviços online que podem usar para a conversão.

Free OCR

 

Este serviço é bastante rápido e eficaz. É um serviço gratuito online de OCR (Reconhecimento Óptico de Caracteres). Com ele pode extrair o texto a partir de qualquer imagem que forneça. Sem registos necessários nem colocação de qualquer email, basta enviar os seus ficheiros em formato imagem. Free-OCR retirar o texto de um JPG, GIF, BMP TIFF ou PDF (somente da primeira página).

A única restrição é que as imagens não devem ser maiores do que 2MB, não superiores a 5000 pixels e há um limite de 10 uploads de imagens por hora.

Free-OCR pode manipular imagens com texto multi-coluna e também suporta vários idiomas: búlgaro, catalão, checo, dinamarquês, holandês, Inglês, finlandês, francês, alemão, grego, húngaro, indonésio, italiano, letão, lituano, norueguês, polaco , português, romeno, russo, sérvio, eslovaco, esloveno, espanhol, sueco, filipino, turco, ucraniano e vietnamita.

OCR Terminal

OCR Terminal é um serviço online OCR que permite converter PDF para Word e imagens JPEG para documentos Word. Uma das suas características relevantes prende-se pela disciplina na formatação, este retém exatamente a formatação e layout dos ficheiros originais. Exporta para Word, PDF, TXT e RTF.

Neste caso já necessita de se registar e para usar o serviço gratuito tem uma limitação de 20 páginas por mês.

Google Docs OCR

 

Google Docs API permite executar o OCR (reconhecimento óptico de caracteres) numa imagem. Há uma demonstração ao vivo, que ilustra esta característica: o utilizador pode carregar uma imagem em alta resolução, nos formatos JPG, GIF ou PNG. Essa imagem deverá ter menos de 10 MB e o texto é extraído no Google Docs, convertendo a imagem num novo documento. A Google refere que “actualmente a operação pode levar até 40 segundos” e um pequeno teste revelou que o serviço ainda não é confiável: é lento e frequentemente apresenta erros. Mas, conhecendo a Gppgle como conhecemos, podemos muito em breve ler um excelente serviço completamente integrado com a suite de produção.

Por hoje fico-me por aqui. Estes serviços gratuitos online já aumentam de sobremaneira as opções para transformar uma folha de papel escrito em texto “editável”. Bom proveito.

Photo Transfer Edge Effect | Photo Effects | PSHERO

 

Step 1

Welcome back my naughty little monkeys! I was up most of the night with this nasty flu that’s been going around, it’s not even noon and already I’m on my third can of Dragon, so if my writing’s a little off kilter, you’ll understand why. Did I just use the word kilter?

Lets get this party started with a visit to iStockPhoto where I found a cool looking stock image of an old medium format film border. There are tons of these available for free as well if you’re willing to put in the time to search. Incase you want to replicate this exact effect you can enter the product id (1249016) into the iStockPhoto search field. The nature of my contract with iStockPhoto doesn’t allow me to give away the original but if you know where to look, I may have “accidentally” left the associated Alpha Channel in the download at the end of the lesson.

Here’s the image I got from iStockPhoto. Did I mention I got it at iStockPhoto?

Step 2

Since I ultimately want to use this image as a mask, lets go ahead and invert the tones by choosing Image>Adjustment>Invert from the main menu, or by simply pressing Command-I (PC: Ctrl-I).

Step 3

What I really want from this image is a true black to transparent mask, but what we’re currently working with is a black and white composite. It’ll take a few steps to do it, but trust me, the result will be worth it. Follow along closely, most of this will be keyboard shortcuts that won’t have any visual reference. Don’t worry, I’ll explain it as we go.

Press Command-A (PC: Ctrl-A) to Select All, then press Command-X (PC: Ctrl-X) to cut the entire image onto the clipboard (Yes, everything will disappear and you’ll be left with a white canvas… it’s ok, that’s what’s supposed to happen).

Now click over to the Channels tab in the Layers palette (*note: If your layers palette isn’t open choose Window>Layers from the main menu). Click the Create New Channel icon at the bottom of the Channels palette to add a new Alpha Channel to the bottom of the list of channels. Click on the new channel to select it and press Command-V (PC: Ctrl-V) to paste the image we cut from the stage into the channel.

Step 4

The advantage of having the black and white image in an alpha channel is that it allows us to load the highlights as a selection where a standard layer will not. Lets do that now by holding down the Command (PC: Ctrl) key and clicking on the layer thumbnail of our new Alpha Channel. Although the selection looks rather random and doesn’t seem to encompass all the white areas of the image, it actually does.

Step 5

With our selection made, lets click up on the RGB channel at the top of the Channels palette to make it active (*note: this will hide the channel we were just working on and make only the selection visible.

Click back to the Layers tab and add a new layer by clicking the Add New Layer icon at the bottom of the layers palette then double click on the layer’s name to rename it Frame.

Step 6

Since our alpha channel allowed us to select only the highlights but what we really want are the shadows, lets go ahead and invert the selection by choosing Select>Inverse from the main menu or by using the keyboard shortcut Command-Shift-I (PC: Ctrl-Shift-I).

Press the D key to reset your foreground color to black and then fill the selection by pressing Option-Delete (PC: Alt-Backspace). We’re now done with the selection, so you can press Command-D (PC: Ctrl-D) to deselect.

Step 7

HERO! You might be saying, this looks just like the image we started with! … and of course that would be true, but things aren’t always as they seem. If I change my background color to red (you don’t need to do this, I’m just illustrating my point). You can see that the black has indeed been separated from the white background and is now isolated for use.

Step 8

Ok, we’ve done all the preparation, now lets get to work on the rest of the effect.

Grab the Polygonal Lasso tool from the Lasso tool fly out menu and clicking from point to point create a nice square selection inside the photo area. This selection doesn’t have to be exact or even, in fact, the less perfect the better. When you get back to your starting point the selection will close itself.

Step 9

Now that the selection is made, lets soften the edges just a touch by choosing Select>Modify>Feather from the main menu (*note: In some older versions of PS the path to the Feather option is Select>Feather.) This is a low resolution example, so I’m going to use a small 2pixel Feather, but if you’re working at a larger resolution you’ll want to adjust accordingly.

Now lets duplicate the selected portion of the layer by pressing Command-J (PC: Ctrl-J). This will put the selection onto it’s own layer above the original. Lets call this layer Photo Holder. In order to see what we’re working with lets also turn off the Frame layer by clicking the eye icon to the right of the layer thumbnail in the Layers palette.

Step 10

The edges of this layer are far too hard for this effect to be convincing, so lets press the E key to invoke the Eraser tool, and then by choosing different brushes from the brush picker we’ll delete small areas around the edge of the photo area. I used a variety of grunge edge brushes to distress my edges and I’m including those Photoshop Brush sets in the download at the end of the lesson. Yes, you’re right, that is very cool of me!

Here’s my Photo Holder layer after all the distressing. Remember that you can rotate the brush tips in the Brushes palette like I taught you in the Rotating Brushes tutorial to make the brushes work for every edge.

Step 11

Lets take a break from this file for a moment and open the photo we will use for the effect. Mrs. Hero took this shot of me on a motorcycle trip to Telluride, Colorado last year. Yes, I look cool, I know.

For this effect I wanted to use a grayscale image (though you don’t have to). Because this tutorial isn’t about black and white conversion I just chose Image>AdjustmentS>Desaturate from the main menu to make it easy. If you want to get into black and white conversion in detail, I’d suggest picking up Scott Kelby’s Photoshop Channels Book and reading Chapter 4 in particular which covers using Calculations for B&W conversion (though the whole book is fantastic).

Step 12

With your photo open, press Command-A (PC: Ctrl-A) to Select All, then Command-C (PC: Ctrl-C) to copy the photo to the clipboard. You can now close your photo if you want by pressing Command-W (PC: Ctrl-W). How’s that for a bunch of keyboard shortcuts mashed into a few lines?

Now that we’ve got the photo copied to the clipboard (no, there’s no actual clipboard, it’s just an expression to let us know that the photo is copied into Photoshops virtual memory), lets return to our working file and more specifically to the Photo Holder layer which should still be selected as the active layer in the Layers palette. And just like we did when we were in the Channels palette, lets go ahead and Command-Click (PC: Ctrl-Click) on the Photo Holder layer icon to load it as a selection.

From the main menu (and this is the cool part) choose Edit>Paste Into. This will take the image we just copied to the “clipboard” and paste it into the selection, creating a new layer and using the selection as a layer mask! How awesome is that?

Step 13

Ok, lets turn on the Frame layer again by clicking in the empty box to the left of the layer thumbnail (the eye icon will reappear long with the layer’s contents). Now technically we don’t need the Photo Holder layer anymore, but I’m going to leave it incase I want to modify it later. I’m also going to name the new layer with the photo on it Photo.

Step 14

With the photo thumbnail selected on the Photo layer I now used the Dodge and Burn tools (found in the Tools bar / keyboard shortcut O) and using a soft edged medium sized round brush with the Range set to Highlights and the Exposure set to around 20% I’m going to darken around the edges and corners (Burn tool) and lighten around the subject (Dodge tool). This effect mimics the old darkroom techniques of dodging and burning an image to get this style of look. Perhaps the subject of a future tutorial, but I won’t be going into any further detail about the technique in this tutorial.

(*note: Dodging and Burning aren’t necessary steps here, and I’ll use a layer style in the next step to mimic the edge burning anyway.)

Step 15

If you don’t feel comfortable using the Burn and Dodge tools too much yet, that’s ok, lets use a layer style to mimic the edge burn effect by double clicking to the right of the layer name in the Layers palette, or by Control-Clicking (PC: Right Click) on the layer and choosing Blending Options to bring up the Layer Styles dialog. Choose Inner Glow from the list on the left (Click on the text, not the checkbox) and add the following settings.

Step 16

Here’s what my image looks like so far.

Step 17

I want the photo to look a little more aged so I’m going to use a fantastic brush (which is included in the download at the end of the lesson) called Scratch Heavy to do a little more distressing.

Create a new layer called Scratches, switch to the Brush tool by pressing the B key, load and select the Scratch Heavy brush and press the D key to reset the foreground color to black. I used the bracket keys [ and ] to size my brush to it was just a little larger than my image, then clicked once on the canvas.

Step 18

Obviously we don’t want the scratches to extend beyond the borders of the photo, so Control-Click (PC: Right-Click) on the Scratches layer and choose Create Clipping Mask from the menu. This will clip the Scratches layer to the Photo layer and the clipping will be indicated by an indentation of the Scratches layer and a small arrow between the two layers. The scratches are a little harsh though, so lets lower the Fill opacity of the Scratches layer to around 30%.

Step 19

The last thing I want to do is add a little sepia tone to the image just to make it feel a little older. Click on the Create New Fill or Adjustment Layer icon at the bottom of the layers palette, choose Photo Filter and choose Sepia from the Filter drop down menu, leave the other settings alone and click OK. Now just Create a Clipping Mask with this layer as well just like we did in Step 18 and you’re done!

Step 20

And that’s it folks, a cool aged photo effect with a nifty edge detail. I hope you learned a little something along the way. I’m off to take a nap.

Through the viewfinder (a Photoshop tutorial of sorts) « Hank & Willie

 

I’m rarely on the bandwagon with photo processing trends, mostly because, well, have you seen the pile of laundry in my living room? And, oh, and these guys keep me a little busy, too.

So while the rest of the photo enthusiasts I love to read were playing with things like selective color, way back when, and texture, sloppy borders, vintage washes and cross processing, I just watched from the sidelines.

But I recently came across this clever technique, called TTV (Through the Viewfinder). Basically, you shoot through the viewfinder of an old camera, using your modern digital or film camera, and create an interesting framing effect in camera. I thought to myself, “That’s kind of fun.”

Apparently hundreds of other people thought the same thing, and decided to make a Flickr group and share their images. You’ll see some AMAZING versions of this technique there.

However, the laundry in my living room didn’t go anywhere, and the 9,000 other things that beckon kept beckoning, so it remained a nice idea until I saw this–a way to do it digitally, without hunting for an old camera to shoot through. Hooray!

So I tried it. And thought I would share the steps with you, since so many of you have taught me wonderful Photoshop techniques.

Hope you’ll share some of your tries with this technique. Or, if you don’t have Photoshop and want me to try on one of your photos, I will pick a few that people send me to try it. (Email me a high-res version at hankandwillieATgmailDOTcom.)

TTV-Through the Viewfinder

1. Find a suitable photo. I loved the old-fashioned feel of the print in her dress, her pigtails and the timeless watermelon-in-summer-moment.

2. Since this effect mimics the old waist-height viewfinders with square pictures, I cropped this one square, even though her buddy was equally cute.

3. Edit to taste. I’ve seen this done with strong, vibrant color, with black and white and with sepia. I went for kind of a mild vintage feel here, using Pioneer Woman’s Soft and Faded action here and reduced the opacity a bit to restore some of the bright color of her watermelon.

4. I opened this file, shared by a very generous photographer out there in Flickrland.There’s a whole group of “through a viewfinder shots” to download here, choose the speckle pattern you like best!

It looks like this:

5. Using layers, drag it on top of your open, edited image, and size it to fit. ( I used free transform.)

6. Choose a blend mode, and voila! (I used multiply, and reduced the opacity to about 80%. You can also try other blending modes, like soft light and hard light for different effects.)

The whole thing took longer to write about than to do. Here are a few other examples.

If you try this, I’d love to see the results, post your link in the comments!

And want to see a super cool way to use this? Photographer Tara Whitney decorated a whole wall with her family photos this way. Wow.

Happy PhotoShopping!

Fim dos desktops daqui a 3 anos

De acordo com o Google sim, em matéria publicada no site silicomrepublic, o chefe do Google na Europa John Herlihy disse que cada vez mais os desktops se tornarão irrelevantes.

“Em três anos, desktops serão irrelevantes, no Japão a maioria das pesquisas hoje são realizadas em smartphones e não em pcs”, disse Herlihy em uma conferência.

As aplicações poderão ser feitas através de dispositivos móveis, não só pelo avanço da tecnologia, mas também pela oportunidade dada pelo cloud-computing.

Com a maioria dos aplicativos e dados armazenados na núvem, os aplicativos não precisam mais ter uma grande capacidade de armazenagem para realizar mais atividades em menos tempo.

Claro que os notebooks ainda serão por muito tempo utilizados principalmente para tarefas mais complicadas de design, desenvolvimento e programação.

Outro fator importante para extinção dos desktops é a popularização dos notebooks e net, que até bem pouco tempo atrás eram restritos a uma parcela da sociedade.

HWiNFO32 Portable

Processador, memória, disco, placa gráfica, BIOS e o resto da família fazem parte do meu computador, verdade? Mas como sei se estão a funcionar correctamente? Como posso saber as suas características, nomes e fabricantes? Provavelmente terei de abrir a máquina ou ler aquele livrinho de 200 páginas que veio na caixa, será assim?

Claro que não. Aliás para quem nos segue estas questões já nem fazem sentido. São tantas as ferramentas que nos permitem ter acesso a estas informações que só mesmo a pedido é que já abrimos o leque para mais uma. Assim foi com o HWiNFO.

Na verdade até tem o seu lugar, esta ferramenta é portátil, logo escusa de pensar que será mais uma aplicação a encher o seu registo. Não, simplesmente descarregue e veja o que lhe pode ser útil tanta informação que lhe será a presentada.

Logo ao abrir a aplicação presenteia-o com um resumo das “entranhas” do seu computador. Será um mundo Matrix? Nem pensar, são apenas os seus componentes devidamente catalogados.

Poderá ter acesso a informações dos seguintes componentes:

  • Processador
  • Motherboard
  • Memória
  • Bus
  • Placa Gráfica
  • Ecrã
  • Drivers
  • Áudio
  • Rede
  • Portas
  • Bateria

Além das descrições dos componentes e dos seus derivados e complementos, a aplicação permite que tenha acesso aos sensores da máquina e receba as temperaturas que cada componente medido está a registar. Sim, é aqui que pode ver se algum está febril.

Além desta pequena pérola, podemos saltar para outra “ostra” e retirar outra pérola também especial: benchmarks. Comparativos que lhe darão uma informação relativa e útil para ter ideia da actualidade e modernidade dos seus componentes face ao mercado.

Mas em caso de “overclock” a algum dispositivo, o ideal será primeiro tirar relatório em modo original, fazer as devidas e cautelosas alterações e depois reportar os novos valores. Pode mesmo exportar a situação da máquina.

Por falar em situação da máquina, estes relatórios são excelentes para quem queira enviar o estado da máquina para um administrador de rede, caso este não consiga ter acesso remoto.

À pouco falei-lhe em overclock… sim eu sei que quem o faz por norma utiliza vários tipos de aplicações deste género, mas não se assuste com a palavra: há por exemplo, software que “esforça” a sua placa gráfica obrigando-a a dar um pouco mais.. digamos que é um overclock controlado. Verifique temperaturas e taxas de esforço.

Novidades desta versão:

  • Melhorada a pesquisa de dispositivos SCSI
  • Adicionado suporte para monitorização QST 2.0
  • Adicionado suporte para LPC secundário
  • Melhorada a monitorização de sensores para EVGA W555
  • Adicionado suporte para o chipset VIA VN1000
  • Actualizado o ficheiro de ajuda
  • Melhorada a monitorização para ASUS M2N-SLI Deluxe.
  • Melhorada a monitorização MSI DKA790GX Platinum (MS-7550).
  • Melhorada a monitorização para AMD 890GX e SB800/Hudson.
  • Melhorado o suporte para VIA VT8261.
  • Melhorada a monitorização na série ASRock: P43DE2, P43iCafe, 770 Extreme3, 770iCafe, M3A790GXH/USB3, 880GMH/USB3, 890GMH/USB3, 890GX Extreme3.
  • Melhorada a monitorização na série ASUS: M4A89GTD-PRO, M4A89GTD-PRO/USB3

Pode ler aqui as restantes novidades desta versão.

Alternativas:

Licença: Freeware
Sistemas Operativos: Windows 9x/2000/XP/Vista/Win7
Download: HWiNFO32 Portable 3.43 [1.7MB]
Download: HWiNFO32 3.43 (Instalação) [2.0MB]
Homepage: Hwinfo

Jogo em Java

Bom hoje nós vamos desenvolver um game educativo bem simples em Java, desenvolvi esse game para ensinar as pessoas que estão começando a mexer no computador e tem problemas com o mouse, ele consiste em vários quadradinhos na tela e a jogador tem que ir passando o mouse no quadradinho vermelho que vai mudando de lugar.

1

O game que vamos desenvolver tem essa aparência, são 30 quadradinhos que ao passar o mouse eles vão mudando de cor, mas eles têm que passar o mouse em uma ordem se não, não tem sentido o game né.

Pronto, vamos por a mão no código ehehehh.

Primeiro vamos criar uma classe para fazer os quadradinhos, então crie a classe Quadrado.

O quadrado tem que ter, posição X, Y, largura, altura, e uma cor.

import java.awt.Color;

public class Quadrado {
        private int x;
        private int y;
        private int width;
        private int height;
        private Color cor;

    public Quadrado(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    public Quadrado(){

        }

    public Color getCor() {
        return cor;
    }

    public void setCor(Color cor) {
        this.cor = cor;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;

    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }  
}

Pronto já temos os quadradinhos precisamos criar agora nossa janela, a janela é mais complicada porque temos que criar um modelo de como vai ser a tela, para depois quando formos criar a tela do game programaremos somente que vamos usar.

A Classe Janela deverá estender a JFrame, pois assim teremos uma janela, precisaremos também implementar duas interfaces a MouseListener e a MouseMotionListener para controlarmos o mouse, deixaremos essa classe abstrata.

Então ficará assim:

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;

public abstract class Janela extends JFrame implements MouseListener, MouseMotionListener{
}

Você não precisa, mas é interessante implementar todos os métodos das classes MouseListener, MouseMotionListener, porque depois só sobrescrevemos só aqueles que vamos usar entendeu??? Hehehhe.

Então até agora a classe Janela está assim:

public abstract class Janela extends JFrame implements MouseListener, MouseMotionListener {

    public void mouseClicked(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {  
    }

    public void mouseDragged(MouseEvent e) {
    }

    public void mouseMoved(MouseEvent e) {
    }
}

Continuando a classe janela precisamos de uma variável para guardar em que fase nos estamos e precisamos também criar os quadradinhos.

    private int numeroDaFase;
    public int getNumeroDaFase() {
        return numeroDaFase;
    }

    public void setNumeroDaFase(int numeroDaFase) {
        this.numeroDaFase = numeroDaFase;
    }

    protected ArrayList<Quadrado> quad = new ArrayList<Quadrado>();

    public ArrayList<Quadrado> getQuad() {
        return quad;
    }

    public void setQuad(ArrayList<Quadrado> quad) {
        this.quad = quad;
     }

Vamos criar inicializar os componentes e fazer um teste?

Para isso precisamos criar mais outro método e depois uma classe, o método é o inicializarComponetes(), assim inicializamos tudo em um único método assim fica mais fácil depois.

public void inicializaComponetes() {
    addMouseListener(this);
    addMouseMotionListener(this);
     setResizable(false);
     setSize(740, 640);
     setTitle(”:: Elzo Brito – Game ::”);
     setDefaultCloseOperation(EXIT_ON_CLOSE);
    show();
}

Agora vamos criar a classe MinhaTela com ela vamos criar a tela, no primeiro momento só para testar a classe Janela depois vamos usar ela para ser nossa tela.

public class MinhaTela extends Janela{

    public MinhaTela(){

        inicializaComponetes();

    }

}

Pronto agora na classe Main crie uma instancia de MinhaTela e veja o que fizemos até agora…

public class Main {

    public static void main(String[] args) {

        MinhaTela mt = new MinhaTela();

    }

}

 

Pode não parecer, mas 50% do nosso game já está pronto J, vamos dar continuidade e desenhar na tela os quadrados que compõe a tela, para isso vamos criar outra classe para facilitar nosso trabalho, criaremos então a classe Fase é nela que estarão os elementos que vamos usar no jogo.

A classe Fase tem um array com 30 quadrados que formarão a tela, alem dos dos métodos setQ() que servirá para setar a posição dos quadrados na classe e getQ() para recuperar os quadrados depois, o construtor da classe cria os 30 quadradinhos já passando a posição que cada um vai estar na tela.

public class Fase {

    private Quadrado[] q = new Quadrado[30];

    public Quadrado[] getQ() {

        return q;

    }

    public void setQ(Quadrado[] q) {

        this.q = q;

    }

    public Fase() {

        Quadrado[] q = new Quadrado[30];

        q[0] = new Quadrado(20, 40, 100, 100);

        q[1] = new Quadrado(140, 40, 100, 100);

        q[2] = new Quadrado(260, 40, 100, 100);

        q[3] = new Quadrado(380, 40, 100, 100);

        q[4] = new Quadrado(500, 40, 100, 100);

        q[5] = new Quadrado(620, 40, 100, 100);

        q[6] = new Quadrado(20, 160, 100, 100);

        q[7] = new Quadrado(140, 160, 100, 100);

        q[8] = new Quadrado(260, 160, 100, 100);

        q[9] = new Quadrado(380, 160, 100, 100);

        q[10] = new Quadrado(500, 160, 100, 100);

        q[11] = new Quadrado(620, 160, 100, 100);

        q[12] = new Quadrado(20, 280, 100, 100);

        q[13] = new Quadrado(140, 280, 100, 100);

        q[14] = new Quadrado(260, 280, 100, 100);

        q[15] = new Quadrado(380, 280, 100, 100);

        q[16] = new Quadrado(500, 280, 100, 100);

        q[17] = new Quadrado(620, 280, 100, 100);

        q[18] = new Quadrado(20, 400, 100, 100);

        q[19] = new Quadrado(140, 400, 100, 100);

        q[20] = new Quadrado(260, 400, 100, 100);

        q[21] = new Quadrado(380, 400, 100, 100);

        q[22] = new Quadrado(500, 400, 100, 100);

        q[23] = new Quadrado(620, 400, 100, 100);

        q[24] = new Quadrado(20, 520, 100, 100);

        q[25] = new Quadrado(140, 520, 100, 100);

        q[26] = new Quadrado(260, 520, 100, 100);

        q[27] = new Quadrado(380, 520, 100, 100);

        q[28] = new Quadrado(500, 520, 100, 100);

        q[29] = new Quadrado(620, 520, 100, 100);

        setQ(q);

    }

}

Agora vamos terminar a classe Janela(), nela vamos criar mais um método e sobrescrever outro, o método que vamos criar é o MyTela(), ele servirá para setar a posição dos quadradinhos na classe janela().

    public void myTela(){

        Fase f = new Fase();

        Quadrado[] q = new Quadrado[30];

        q = f.getQ();

        for(int i=0;i<30;i++){

            q[i].setCor(Color.BLACK);

            quad.add(q[i]);

        }

        q[0].setCor(Color.red);

    }

Pronto ele cria uma instancia de fase e adiciona no nosso ArrayList a posição de todos os quadradinhos, agora precisamos sobrescrever o método Paint(Graphics g) ele é responsável por desenhar a tela e como queremos desenhar os quadradinhos na tela então precisamos dar uma arrumada nele.

    @Override

    public void paint(Graphics g) {

        g.setColor(Color.WHITE);

        g.fillRect(0, 0, 20, 650);

        g.fillRect(120, 0, 20, 650);

        g.fillRect(240, 0, 20, 650);

        g.fillRect(360, 0, 20, 650);

        g.fillRect(480, 0, 20, 650);

        g.fillRect(600, 0, 20, 650);

        g.fillRect(720, 0, 20, 650);

        g.fillRect(0, 0, 740, 40);

        g.fillRect(0, 140, 740, 20);

        g.fillRect(0, 260, 740, 20);

        g.fillRect(0, 380, 740, 20);

        g.fillRect(0, 500, 740, 20);

        g.fillRect(0, 620, 740, 20);

        for(int i=0;i<30;i++){

            g.setColor(quad.get(i).getCor());

            g.fill3DRect(quad.get(i).getX(), quad.get(i).getY(), quad.get(i).getWidth(), quad.get(i).getHeight(), true);

        }

    }

Quase pronto vamos alterar o método inicializaComponentes() para chamar o MyTela() pois se não, não conseguiremos desenhar a tela sem a posição dos quadradinho correto???

    public void inicializaComponetes() {

        addMouseListener(this);

        addMouseMotionListener(this);

        setResizable(false);

        setSize(740, 640);

        setTitle(”:: Elzo Brito – Game ::”);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        myTela();

        show();  

    }

Como será que a tela ficou??

 

Só falta agora a lógica do game, como havíamos pensando antes, o nosso game é para pessoas que não sabem mexer com o mouse então quando passar o mouse no quadradinho vermelho ele tem que mudar de lugar forçando a pessoa a seguir-lo com o mouse, vamos então para a classe MinhaTela() pois é nela que iremos por um pouco da lógica do nosso game.

    public void pintarQuad(int x){

        try {

            if (quad.get(x – 1).getCor() == Color.ORANGE) {

                quad.get(x + 1).setCor(Color.RED);

                quad.get(x – 1).setCor(Color.PINK);

                quad.get(x).setCor(Color.ORANGE);

            }

        }

        catch(java.lang.ArrayIndexOutOfBoundsException ex){

            if(quad.get(0).getCor() == Color.RED){

                quad.get(1).setCor(Color.RED);

                quad.get(0).setCor(Color.ORANGE);

            }

        }

        catch(java.lang.IndexOutOfBoundsException ex){}

        repaint();

    }

Adicione esse método pintarQuad(int x), ele serve para pintar o quadrado onde passamos o mouse, se passamos o mouse no 1º quadradinho ele deve ficar amarelo e o 2º quadradinho deve ficar vermelho se passarmos o mouse no 2º quadradinho ele deve ficar amarelo o 3º quadradinho deve ficar vermelho e o 1º quadradinho fica rosinha.

Para finalizar precisamos do movimento do mouse correto? Isso então vamos criar uma classe para trabalharmos só com o movimento do mouse, vamos criar então a classe FaseMouseMove() nela trabalharemos o movimento do mouse sobre os quadradinhos, ela deve importar o MouseEvent, estender a MinhaTela() e sobrescrever o método mouseMoved(MouseEvent e).

import java.awt.event.MouseEvent;

public class FaseMouseMove extends MinhaTela{

    @Override

    public void mouseMoved(MouseEvent e) {

        for(int i=0;i<30;i++){

            if(e.getX() > quad.get(i).getX() && e.getX() < (quad.get(i).getWidth() + quad.get(i).getX()) && e.getY() > quad.get(i).getY() && e.getY() < (quad.get(i).getHeight()+quad.get(i).getY())){

                pintarQuad(i);

            }

        }

    }

}  

Esse IF gigante testa a condição do ponteiro do mouse, se o ponteiro do mouse estiver dentro do quadradinho ele chama então o metodo pintarQua(int i) passando o número do quadradinho que o mouse estar em cima, pronto o game esta criado basta apenas criar uma instancia da classe FaseMouseMove() na classe Main() e pronto é só jogarrrr

public class Main {

    public static void main(String[] args) {

        FaseMouseMove fmm = new FaseMouseMove();

    }

}

 

Pronto galera espero que tenham gostado do artigo, quem quiser fazer o download do projeto basta clicar no link abaixo, ele foi desenvolvido no NetBeans.

http://elzobrito.com/arquivos/desenvolvimento/gameeducativo/GameEducativo.zip

HTML 5

Beleza pessoal? Depois de mais de um ano sem escrever aqui no MX Studio, volto falando sobre a nova versão do HTML.

Vamos lá!

O HTML 5 veio com grandes novidades, podendo até substituir algumas funções que normalmente era utilizado no flash, como player de audio ou vídeo, por exemplo. A nova versão e muito mais robusta, antes para estruturar um documento, era usado div’s com o atributo id, para identificar cada parte do site, agora na nova versão isso foi melhorado, para cada parte da estrutura existe uma tag especifica, o que deixa o código muito mais estruturado. Abaixou vou mostrar dois exemplos, como era no HTML 4 e como é agora na nova versão. Também vou listar algumas novas tags.

Sintaxe HTML 4 x HTML 5:

HTML 4

<?xml version=”1.0″ encoding=”UTF-8″?>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<title>Titulo do Documento</title>

</head>

<body>

</body>

</html>

HTML 5

<?xml version=”1.0″ encoding=”UTF-8″?>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<title>Titulo do Documento</title>

</head>

<body>

<header>Topo</header>

<nav>Menu de Navegação</nav>

<article>Conteudo</article>

<footer>Rodapé</footer>

</body>

</html>

Abaixo segue as novas tags.

  • selection – representa um documento genérico ou seleção de tags. Pode ser usado em conjunto com os elementos h1, h2, h3, h4, h5 e h6.
  • article – representa um pedaço independente do conteúdo de um documento, como um blog ou artigo de jornal.
  • aside – representa uma parte do conteúdo que é apenas ligeiramente relacionado com o restante da página.
  • hgroup – representa o cabeçalho de uma seção.
  • footer – representa um rodapé para uma seção e pode conter informações sobre o autor, copyright,…
  • nav – representa uma seção do documento destinada à navegação.
  • figure – pode ser usado para associar uma legenda junto com algum documento incorporado, como uma imagem ou vídeo.

<figure>

<video src=”ogg”></video>

<figcaption>Example</figcaption>

</figure>

  • figcaption – fornece a legenda.
  • video e audio para conteúdos multimídia.
  • embed – plugins.
  • marker – representa uma série de texto marcado.
  • progress – representa uma conclusão de uma tarefa, como baixar ou executar uma série de operações.
  • meter – representa uma medida, como o uso do disco.
  • time – representa uma data e/ou tempo.
  • ruby rb e rp – permite a marcação de anotações de Ruby.
  • canvas – é utilizada para renderização de gráficos bitmap.
  • command – representa um comando que o usuário pode invocar.
  • details – representa informações adicionais ou controles que o usuário pode obter sobre uma procura. O elemento summary fornece um resumo.
  • datalist – em conjunto com o atributo list usado na tag input pode ser usada para fazer caixas de combinação:

<input list=”browsers”>

<datalist>

<option value=”Safari”>

<option value=”Internet Explorer”>

<option value=”Opera”>

<option value=”Firefox”>

</datalist>

Isso só foi uma amostra da nova versão, nos próximos artigos vou estar mostrando como utilizar a nova versão do HTML 5.

Até++!