রবিবার, ১৬ অক্টোবর, ২০১১

Scroll Canvas in J2ME


It is fun to draw image, line, rectangle or strings in j2me. Sometimes objects we are drawing is larger than the screen (which is displayed). In that case we need to scroll the canvas to view the complete object. In order to do this we need to get the user keystroke and move the canvas according to key stroke.
In this tutorial we are displaying a large image and move it using up/down or left/right key.
We are using the following method to get key-stroke from user:

    public void keyReleased(int keyCode)
    {
        this.keyCode=keyCode;       
        int gameKey = getGameAction(keyCode);
        this.gameKey=gameKey;
        if ((gameKey == UP) || (keyCode == KEY_NUM2))
        {
            imgY+=5;
            //Moving Up 5 pixel here.
        }
        else if ((gameKey == LEFT) || (keyCode == KEY_NUM4))
        {
            imgX+=5;
            //Moving Left 5 pixel here.
        }
        else if ((gameKey == RIGHT) || (keyCode == KEY_NUM6))
        {
            imgX-=5;
            //Moving Right 5 pixel here.
        }
        else if ((gameKey == DOWN) || (keyCode == KEY_NUM8))
        {
            imgY-=5;
            //Moving Down 5 pixel here.
        }

        repaint();
        serviceRepaints();
    } 

Then in paint method we are passing the imgX and imgY variable and we are setting x coordinate of the image to imgX and y coordinate of the image to imgY. So that while we are moving image using up/down or left/right our image is moving. The pant method is as following:

    protected void paint(Graphics g)
    {
        this.g=g;
        try
        {
            imagePart = Image.createImage("/Education.jpg");
        }
        catch (IOException ex)
        {
            g.setColor(0xffffff);
            g.drawString("Failed to load image!", 0, 0, Graphics.TOP | Graphics.LEFT);
            return;
        }

        g.drawImage(imagePart, imgX,imgY, Graphics.TOP | Graphics.LEFT);
    }

I think it can help you. The source code of this project can be found from here.

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন