2014-06-20 73 views
1

我使用此代碼在畫布上繪製多邊形。但是我想計算多邊形的面積。當然給每條線的測量。我在地圖上看到很多示例,但是ı不要在畫布上進行轉換/調整。任何人都可以顯示一種方式或方法?Android使用畫布繪製計算多邊形的面積(不是地圖)

在此先感謝。

import java.util.ArrayList; 
import java.util.List;  
import android.app.Activity; 
import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.graphics.Paint.Style; 
import android.graphics.Point; 
import android.os.Bundle; 
import android.view.MotionEvent; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 

public class MainActivity extends Activity 
{ 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(new DrawingView(MainActivity.this)); 
    } 

    class DrawingView extends SurfaceView 
    { 
     private 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.BLACK); 
      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.WHITE); 

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

         // Draw points 
         canvas.drawCircle(current.x, current.y, 5, 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); 
          canvas.drawLine(next.x, next.y, first.x, first.y, paint); 
          c 
         } 

        } 

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

例如(而不是畫布)XY繪圖佈局。 – serifsadi

回答

2

下面是一個計算多邊形面積的方法。

for (int i = 0; i < points.size(); i++) { 
    float addX = points.get(i).x; 
    float addY = points.get(i == points.size() - 1 ? 0 : i + 1).y; 
    float subX = points.get(i == points.size() - 1 ? 0 : i + 1).x; 
    float subY = points.get(i).y; 
    total += (addX * addY * 0.5); 
    total -= (subX * subY * 0.5); 
} 
return Math.abs(total); 
+0

感謝您的回答。 – serifsadi