You Are Here:

Community: Wiki

This page was last modified on 15 September 2009, at 11:32.

How to Fit an Image to the Screen Size

From Forum Nokia Wiki

Reviewer Approved   
Image:Screens22.jpg

If we want to use an image as background in a J2ME application, we have the problem that we must to have one image for each different size screen. Another approach is to have only one image and fit it to all screen sizes.

In this article I will describe an algorithm to do that.

Method Specification

Method Name CreateScaledImage
Parameters
imgOldImage Image that we have to fit
iNewWidth The new witdth of the image
iNewHeight The new height of the image
Return Value
New image with the new size

Source file

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];
 
iOldRGBArray = 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;
 
}

Example

We could use this method in a Canvas Object in this way:

public class MyCanvas extends GameCanvas
{
private Image objBKGImage = null;
 
public void paint(Graphics g)
{
 
 
iViewH = this.getHeight();
iViewW = this.getWidth();
 
 
 
// load the background image
if (objBKGImage== null)
{
try
{
 
objBKGImage = Image.createImage("/res/Logo_150_53.png");
 
objBKGImage = CreateScaledImage(objBKGImage, iViewW, iViewH)
 
} catch (IOException ex)
{
ex.printStackTrace();
}
}
 
 
 
// draw background
if (objBKGImage!= null)
g.drawImage(objBKGImage,
(int)iViewW / 2,
(int)iViewH / 2,
Graphics.VCENTER | Graphics.HCENTER );
 
}
}

Microedition 19:39, 28 August 2008 (EEST) -- http://microedition.biz

Rate This

 
Bookmark this page: DeliciousDiggFacebookGoogleYahooStumbleUponRedditDiigoTechnocratiTwitter  Share this page Share this page Print this Page Print this page Invite a friend Invite a friend
京ICP备05048969号    Email Newsletters Press Terms & Conditions Privacy Policy Sitemap Contact Us © 2009 Nokia