【问题标题】:How to draw large image in canvas and move upon key event如何在画布中绘制大图像并在关键事件上移动
【发布时间】:2012-02-16 21:34:28
【问题描述】:

我有一张大图。此图像有一些供用户使用的文本。所以我不能调整图像大小以适应较小的屏幕。图像远大于设备屏幕尺寸。我的意图是在画布中绘制完整的图像而不包含大小。我想在用户按键事件(左、右、上、下)时一点一点地移动图像,比如滚动。

我可以通过以下方式在画布中绘制图像:-

g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);

我不知道如何根据按键事件来带动图片的其他部分如滚动。
我见过很多具有这种功能的 j2me 游戏。
在哪里可以找到这些信息?

【问题讨论】:

标签: image java-me midp lcdui


【解决方案1】:

您可以使用Pngcrush它的主要目的是通过尝试各种压缩级别和PNG过滤器方法来减小PNG IDAT数据流的大小。如果宽度或长度的大小非常大并且您打算将其绘制在画布上,创建图像后,您可以在canvas的paint方法中使用Graphics的drawRegion方法在其上绘制所需的图像。您可以通过更改参数来更改绘制的图像(例如当用户按键时) drawRegion() 方法和重绘画布:

public class CanvasButterfly extends Canvas implements ... {


private int ix, iy;
//image
private Image picture;
/*
* Constructor
*/
public CanvasButterfly() {
    init();
}

/* Function   : paint(Graphics)
* Description : This method is used for rendering Graphics
* Input       : Graphics
* return      : Void
*/
protected void paint(Graphics g) {
    g.setColor(255, 255, 255);
    g.fillRect(0, 0, this.getWidth(), this.getHeight());
    if (picture != null) {
        g.drawRegion(picture, ix, iy,
              picture.getWidth() - ix, picture.getHeight() - iy,
              Sprite.TRANS_NONE, 0, 0, Graphics.TOP | Graphics.LEFT);
    }
}

/* Function   : moveImage(int)
* Description : This method handle Canvas events
* Input       : void
* return      : Void
*/
private void moveImage(int keyCode) {

    int key = -1;

    try {
        key = getGameAction(keyCode);
    } catch (Exception ex) {
        key = keyCode;
    }

    switch (key) {
        case Canvas.DOWN:
            iy = Math.min(iy + 1,picture.getHeight());
            break;
        case Canvas.UP:
            iy = Math.max(iy - 1,0);
            break;
        case Canvas.LEFT:
            ix = Math.max(ix - 1,0);
            break;
        case Canvas.RIGHT:
            ix = Math.min(ix + 1,picture.getWidth());
            break;
    }

}

//keyPressed 
public void keyPressed(int keyCode) {
    moveImage(keyCode);
    repaint();
}
//keyRepeated
public void keyRepeated(int keyCode) {
    moveImage(keyCode);
    repaint();
}

/* Function   : init()
* Description : This method initialized the class objects
* Input       : void
* return      : Void
*/
private void init() {
//
    ix = ...
    iy = ...

    try {
            picture= Image.createImage("/" + image + ".png");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
}

这里,第一次从画布中的坐标(ix,iy)绘制图片。

【讨论】:

    猜你喜欢
    • 2015-12-03
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2019-10-19
    • 2018-12-30
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多