簡體   English   中英

增強幾何:多邊形定義

[英]Boost-geometry : Polygon definition

您能否告訴我為什么這個多邊形定義不起作用?

namespace bg = boost::geometry;

int main()
{
typedef bg::model::point<double, 2, bg::cs::cartesian> point_type;
typedef bg::model::polygon<point_type> polygon_type;

polygon_type P;

int xi[] = {0,100,100,0,0};
int yi[] = {0,0,100,100,0};

bg::append(P, bg::make<point_type>(*xi, *yi));

double area = bg::area(P);
std::cout << "Area:" << area << std::endl;

Return 0; }

這顯示面積:0

謝謝

學習使用庫來診斷您的問題:

std::string reason;
bool ok = bg::is_valid(P, reason);
std::cout << "Polygon " << (ok?"valid":"invalid") << " (" << reason << ")\n";

版畫: Coliru直播

Polygon invalid (Geometry has too few points)

您也可以在WKT / DSV(甚至SVG)中打印幾何圖形: Live On Coliru

POLYGON((0 0)) invalid (Geometry has too few points)
Area:0

這使問題更加明顯。


您不想添加單個點,而是添加一個環。 實現此目的的最簡單方法是顯式使其成為環:

ring_type points {
    {   0,   0 },
    { 100,   0 },
    { 100, 100 },
    {   0, 100 },
    {   0,   0 },
};

bg::append(P, points);

仍然不行,但更好: Live on Coliru

POLYGON((0 0,100 0,100 100,0 100,0 0)) invalid (Geometry has wrong orientation)
Area:-10000

如您所見,我們弄錯了方向(應該是順時針方向):

ring_type points {
    {   0,   0 },
    {   0, 100 },
    { 100, 100 },
    { 100,   0 },
    {   0,   0 },
};

版畫: Coliru直播

POLYGON((0 0,0 100,100 100,100 0,0 0)) valid (Geometry is valid)
Area:10000

注意您可以使用bg::correct來糾正在簡單情況下的有效性問題,例如這樣。

樣式和類型

實際上,環形是多邊形類型的外環類型:

static_assert(std::is_same<ring_type, polygon_type::ring_type>{}, "synonyms");
static_assert(bg::point_order<ring_type>::value == bg::order_selector::clockwise, "orientation");

因此,您可以直接從外環初始化程序構造:

polygon_type P { {
    {   0,   0 },
    {   0, 100 },
    { 100, 100 },
    { 100,   0 },
    {   0,   0 },
} };

將整個程序壓縮為一行: Live On Coliru

int main() {
    typedef bgm::polygon<bgm::d2::point_xy<double> > polygon_type;
    std::cout << "Area:" << bg::area(polygon_type { { {0, 0}, {0, 100}, {100, 100}, {100, 0}, {0, 0} } }) << std::endl;
}

或者,您也可以從WKT / DSV上閱讀它: Live On Coliru

int main() {
    bgm::polygon<bgm::d2::point_xy<double> > P;
    bg::read_wkt("POLYGON((0 0,0 100,100 100,100 0,0 0))", P);
    std::cout << "Area:" << bg::area(P) << std::endl;
}

仍在打印

Area:10000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM