开发者

Android: How to draw simple graphics on a large scrolling canvas

In Android, I need to be able to draw simple graphics (points, lines, circles, text) on a large scrollable canvas (i.e the phone's screen is a viewport in a much larger area). I have hunted for tutorials on how to do this without success.

"World Map FREE" on Android market is a good example of the sort of effect I need to achieve.

This must be a common problem, so I'm surprised I c开发者_运维问答an't find examples.


I've had to implement something fairly recently of this sort. Basically I had coordinates in my custom view that would shift where objects would be drawn, via some auxiliarry functions:

public class BoardView extends View {

    //coordinates to shift the view by
    public float shiftX=0f;
    public float shiftY=0f;

    //used in the dragging code
    public float lastX=-1f;
    public float lastY=-1f;

    /*...*/

    //functions that take into account the shifted x and y values
    //pretty straightforward
    final public void drawLine(Canvas c,float x1,float y1,float x2,float y2,Paint p){
        c.drawLine(x1+shiftX, y1+shiftY, x2+shiftX, y2+shiftY, p);
    }

    final public void drawText(Canvas c,String s,int x,int y,Paint p){
        c.drawText(s, x+shiftX, y+shiftY, p);
    }

    /*etc*/

To actually implement the dragging, I wrote a custom onTouchEvent method to implement dragging:

public boolean onTouchEvent(MotionEvent event){
        int eventaction=event.getAction();
        float x=event.getX();
        float y=event.getY();
        switch(eventaction){
        case MotionEvent.ACTION_DOWN:
            time=System.currentTimeMillis();//used in the ACTION_UP case
            break;
        case MotionEvent.ACTION_MOVE:
            if(lastX==-1){ lastX=x;lastY=y;}//initializing X, Y movement
            else{//moving by the delta
                if(Math.abs(x-lastX)>1 || Math.abs(y-lastY)>1){//this prevents jittery movement I experienced
                    shiftX+=(x-lastX);//moves the shifting variables
                    shiftY+=(y-lastY);//in the direction of the finger movement
                    lastX=x;//used to calculate the movement delta
                    lastY=y;
                    invalidate();//DON'T FORGET TO CALL THIS! this redraws the view
                }
            }
            break;
        case MotionEvent.ACTION_UP: //this segment is to see whether a press is a selection click(quick press)
        //or a drag(long press)
            lastX=-1;
            if(System.currentTimeMillis()-time)<100)
                try {
                    onClickEvent(x,y);//custom function to deal with selections
                } catch (Exception e) {
                    e.printStackTrace();
                }
            break;
        }
        return true;
    }


Look into tile engines, there's a lot to find on Google about them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜