This J2ME tip explains how to place an image without knowing the size of the image. If you need this information, you can get it from the Image's getWidth() and getHeight() methods.


class DrawImageCanvas extends Canvas {
    
    static Image image;
    int count;
    
    public void paint(Graphics g) {
        
        int width = getWidth( );
        int height = getHeight( );
        
        // Fill the background using black
        g.setColor(0);
        g.fillRect(0, 0, width, height);
        
        // Load an image from the MIDlet resources
        if (image == null) {
            
            try {
                
                image = Image.createImage("resources/earth.png");
                
            } catch (IOException ex) {
                
                g.setColor(0xffffff);
                g.drawString("Failed to load image!", 0, 0, Graphics.TOP |
                        Graphics.LEFT);
                return;
            }
        }
        
        switch (count % 3) {
            
            case 0:
                // Draw the image at the top left of the screen
                g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);
                break;
            
            case 1:
                // Draw it in the bottom right corner
                g.drawImage(image, width, height, Graphics.BOTTOM |
                        Graphics.RIGHT);
                break;
            
            case 2:
                // Draw it in the center
                g.drawImage(image, width/2, height/2, Graphics.VCENTER |
                        Graphics.HCENTER);
        }
        
        count++;
    }
    
}

 

 

 

 Related Tips