给定一个多边形的坐标,如果计算这个多边形围起来的面积?
专栏:iLoveIC July 17, 2026, 2:22 p.m. 8 阅读
利用鞋带公式计算多边形面积

给一个多边形的坐标,如果计算这个多边形围起来的面积?

利用鞋带公式,面积 = 0.5 * |sum (x_i y_{i+1} - y_i x_{i+1})|,只要知道一圈拐点的坐标,就可以算出面积。

下面写了一个tcl函数proc calc_area {loc_list} { ... }来实现,代码中有注释。

#!/usr/bin/env tclsh

# 计算简单多边形面积(鞋带公式),支持凹凸任意形状
# 输入:loc_list = 平铺的 x1 y1 x2 y2 ... 浮点数列表(单位:um)
# 返回:面积值(浮点数,单位:um²)
proc calc_area {loc_list} {
    set n [llength $loc_list]
    if {$n < 6} {
        error "至少需要 6 个数字(3 个坐标点),当前有 $n 个"
    }
    if {$n % 2 != 0} {
        error "坐标数字个数必须为偶数,当前为 $n"
    }

    # 两两配对成坐标点列表
    set coords {}
    for {set i 0} {$i < $n} {incr i 2} {
        set x [lindex $loc_list $i]
        set y [lindex $loc_list [expr {$i + 1}]]
        lappend coords [list $x $y]
    }

    # 如果首尾坐标相同,去掉最后一个重复点
    set first [lindex $coords 0]
    set last  [lindex $coords end]
    if {[lindex $first 0] == [lindex $last 0] && [lindex $first 1] == [lindex $last 1]} {
        set coords [lrange $coords 0 end-1]
    }

    set m [llength $coords]
    if {$m < 3} {
        error "有效坐标点数不足 3 个"
    }

    set sum 0.0
    for {set i 0} {$i < $m} {incr i} {
        set j [expr {($i + 1) % $m}]
        set xi [lindex $coords $i 0]
        set yi [lindex $coords $i 1]
        set xj [lindex $coords $j 0]
        set yj [lindex $coords $j 1]
        set sum [expr {$sum + $xi * $yj - $yi * $xj}]
    }

    set area [expr {0.5 * abs($sum)}]
    return $area
}

# ============ 使用你的数据 ============
set polygon_coords {
    267.83 276.925
    267.83 1157.7
    348.075 1157.7
    348.075 1383.375
    194.215 1383.375
    194.215 1719.355
    844.945 1719.355
    844.945 1660.43
    1170.64 1660.43
    1170.64 1558.32
    1680.59 1558.32
    1680.59 1177.78
    1494.42 1177.78
    1494.42 787.09
    1680.59 787.09
    1680.59 339.76
    1523.75 339.76
    1523.75 276.925
}

set area [calc_area $polygon_coords]
puts "多边形面积 = $area  um²"
感谢阅读,更多文章点击这里:【专栏:iLoveIC】
最新20篇 开设专栏