Como ajustar uma imagem ao tamanho da tela
Dados do artigo
Artigo
Tradução:
Originado de How to Fit an Image to the Screen Size
Por maiconherverton
Última alteração feita por hamishwillee
em 08 Dec 2011
Se quisermos usar uma imagem como fundo em uma aplicação J2ME, temos o problema de ter uma imagem para cada tamanho de tela diferente. Outra abordagem é ter apenas uma imagem e ajustá-la para todos os tamanhos de tela.
Neste artigo irei descrever um algoritmo para fazer isso.
Descrição do metódo
| Nome do método | CreateScaledImage |
| Parâmetros | |
| imgOldImage | Imagem que temos que encaixar |
| iNewWidth | A nova largura da imagem |
| iNewHeight | A nova altura da imagem |
| Retorne o valor | |
| Nova imagem com o novo tamanho | |
Código
public static Image CreateScaledImage( Image imgOldImage, int iNewWidth, int iNewHeight )
{
Image imgNewImage = null;
final int iOldWidth = imgOldImage.getWidth();
final int iOldHeight = imgOldImage.getHeight();
int iOldRGBArray[] = new int[iOldWidth * iOldHeight];
imgOldImage.getRGB( iOldRGBArray, 0, iOldWidth, 0, 0, iOldWidth, iOldHeight);
int iNewRGBArray[] = new int[iNewWidth * iNewHeight];
for (int yy = 0; yy < iNewHeight; yy++)
{
int dy = yy * iOldHeight / iNewHeight;
for (int xx = 0; xx < iNewWidth; xx++)
{
int dx = xx * iOldWidth / iNewWidth;
iNewRGBArray[(iNewWidth * yy) + xx] = iOldRGBArray[(iOldWidth * dy) + dx];
}
}
imgNewImage = Image.createRGBImage(iNewRGBArray, iNewWidth, iNewHeight, true);
return imgNewImage;
}
Exemplo
Nós poderíamos usar esse método em um objeto do tipo Canvas, da seguinte maneira:
public class MyCanvas extends GameCanvas
{
private Image objBKGImage = null;
public void paint(Graphics g)
{
iViewH = this.getHeight();
iViewW = this.getWidth();
// carrega o background da imagem
if (objBKGImage== null)
{
try
{
objBKGImage = Image.createImage("/res/Logo_150_53.png");
objBKGImage = CreateScaledImage(objBKGImage, iViewW, iViewH)
} catch (IOException ex)
{
ex.printStackTrace();
}
}
// desenha o background
if (objBKGImage!= null)
g.drawImage(objBKGImage,
(int)iViewW / 2,
(int)iViewH / 2,
Graphics.VCENTER | Graphics.HCENTER );
}
}

