Android:如何在大型滚动 Canvas 上绘制简单图形

标签 android graphics scroll

在 Android 中,我需要能够在大型可滚动 Canvas (即手机屏幕是更大区域的视口(viewport))上绘制简单图形(点、线、圆、文本)。我一直在寻找有关如何执行此操作但未成功的教程。

Android 市场上的“World Map FREE”是我需要实现的那种效果的一个很好的例子。

这一定是一个常见问题,所以我很惊讶找不到示例。

最佳答案

我最近不得不实现这类东西。基本上我的自定义 View 中有坐标,可以通过一些辅助函数移动对象的绘制位置:

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*/

为了实际实现拖动,我编写了一个自定义的 onTouchEvent 方法来实现拖动:

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;
    }

关于Android:如何在大型滚动 Canvas 上绘制简单图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6493791/

相关文章:

android - 无法解析依赖 Android Studio 3.0

android - 有什么办法可以监听相机加载时的声音吗? CWAC相机

.net - 图形 GDI+ 上的多线程

c# - 滚动面板时在 winform 面板中绘制按钮

html - 使用 Chrome 防止水平触摸板在 macbook 上滚动?

css - 相对于滚动区域的位置

android - 应用程序 :stackFromEnd for RecyclerView is not working in xml?

android - 如何在android中创建自定义形状的按钮

java - 我应该使用什么来显示游戏图形?

java - 为什么 fill3DRect 在我自己的计算机之外的其他计算机上无法正常工作?