gpt4 book ai didi

Android使用 Canvas 绘图(不是 map )计算多边形的面积

转载 作者:行者123 更新时间:2023-11-29 21:06:36 26 4
gpt4 key购买 nike

我使用此代码在 Canvas 上绘制多边形。但我想计算多边形的面积。当然给出每条线的测量值。我在 map 上看到很多示例,但我不会在 Canvas 上进行转换/改编。任何人都可以展示一种方式或方法吗?

提前致谢。

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

最佳答案

这是计算多边形面积的方法。

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

关于Android使用 Canvas 绘图(不是 map )计算多边形的面积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24333969/

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