1

大家好,我是 blackebry 的新手。我想使用低级图形来绘制位图字段。在这个位图字段上,我需要采取三个行动-

  1. 选择位图字段,
  2. 在屏幕中向任何方向拖动它,然后
  3. 最后在屏幕上的任意位置释放它。

我怎样才能做到这一点。如果'Canvas'可以成为一个解决方案......任何人都可以帮助我提供一些关于如何使用'Canvas'的示例代码。

还有其他方法可以制作可拖动的位图字段..??

请帮忙

4

1 回答 1

0

首先,您可以创建位图并从中获取图形对象以在其上进行自定义绘图。

Bitmap myBitmap = new Bitmap(widht, height);
Graphics graphics = Graphics.create(myBitmap);

// now you can draw anything on graphics supported by API

[已编辑]

我添加了一个用于在屏幕上拖动图像的代码片段。如果它对您有用,您可以检查此代码。

class MyScreen extends MainScreen {
    private final Bitmap myBm;
    private int wBm;
    private int hBm;
    private int xBm;
    private int yBm;
    private boolean dragStarted;

    public MyScreen() {
        myBm = Bitmap.getBitmapResource("img/myBitmap.png");
        if (myBm != null) {
            wBm = myBm.getWidth();
            hBm = myBm.getHeight();
        }
    }

    protected void paint(Graphics graphics) {
        // need to adjust z-index of the items added on screen.
        super.paint(graphics);
        if (myBm != null) {
            graphics.drawBitmap(xBm, yBm, wBm, hBm, myBm, 0, 0);
        }
    }

    protected boolean touchEvent(TouchEvent event) {
        int x = event.getX(1);
        int y = event.getY(1);
        int eventCode = event.getEvent();

        if (dragStarted == false & (eventCode == TouchEvent.DOWN)) {
            if (isDragActivated(x, y)) {
                // need to adjust offset.
                dragStarted = true;
                updateBitmapLocation(x, y);
            }
        }

        if (eventCode == TouchEvent.MOVE && dragStarted) {
            updateBitmapLocation(x, y);
        }

        if (eventCode == TouchEvent.UP && dragStarted) {
            dragStarted = false;
            updateBitmapLocation(x, y);
        }

        // need to decide what to return
        return true;
    }

    private void updateBitmapLocation(int xTouch, int yTouch) {
        if (xTouch != xBm && yTouch != yBm) {
            xBm = xTouch;
            yBm = yTouch;
            invalidate();
        }
    }

    private boolean isDragActivated(int x, int y) {
        return (x >= xBm && x <= xBm + wBm && y >= yBm && y <= yBm + hBm);
    }
}
于 2012-02-01T11:10:55.737 回答