gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:23:52 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com