Android在屏幕上绘制对象并获取几何数据

时间:2012-11-09 09:53:22

标签: android geometry draw calculator

是否有人通过顶点绘制对象的经验,例如多边形并获得它们的表面和周长。

将使用类似于https://play.google.com/store/apps/details?id=de.hms.xconstruction的顶点或坐标手动绘制几何体,然后形成形状。我需要获得这些封闭形状的表面。

网上有没有可用的例子?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我认为下面这段代码可能是一个好的开始。它基本上在所有用户触摸之间绘制线条:

public class TestActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new DrawingView(this));
}

class DrawingView extends SurfaceView {

    private final SurfaceHolder surfaceHolder;
    private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private List<Point> pointsList = new ArrayList<Point>();

    public DrawingView(Context context) {
        super(context);
        surfaceHolder = getHolder();
        paint.setColor(Color.WHITE);
        paint.setStyle(Style.FILL);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (surfaceHolder.getSurface().isValid()) {

                // Add current touch position to the list of points
                pointsList.add(new Point((int)event.getX(), (int)event.getY()));

                // Get canvas from surface
                Canvas canvas = surfaceHolder.lockCanvas();

                // Clear screen
                canvas.drawColor(Color.BLACK);

                // Iterate on the list
                for(int i=0; i<pointsList.size(); i++) {
                    Point current = pointsList.get(i);

                    // Draw points
                    canvas.drawCircle(current.x, current.y, 10, paint);

                    // Draw line with next point (if it exists)
                    if(i + 1 < pointsList.size()) {
                        Point next = pointsList.get(i+1);
                        canvas.drawLine(current.x, current.y, next.x, next.y, paint);
                    }
                }

                // Release canvas
                surfaceHolder.unlockCanvasAndPost(canvas);
            }
        }
        return false;
    }

}