C# 由左上、右下两个坐标点计算矩形的长、宽以及两点的距离

一、计算长、宽

直接使用坐标点计算

// 定义矩形左上角和右下角的坐标
Point topLeft = new Point(0, 0);
Point bottomRight = new Point(5, 10); 

// 计算矩形的长和宽
int width = bottomRight.X - topLeft.X;//矩形宽度
int height = bottomRight.Y - topLeft.Y;//矩形高度

或是创建一个Rectangle,然后获取宽、高

//或是创建一个Rectangle。然后获取宽、高
System.Drawing.Point topLeft = new Point(0, 0);
System.Drawing.Point bottomRight = new Point(5, 10); 
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(topLeft.X, topLeft.Y, bottomRight.X - topLeft.X, bottomRight.Y - topLeft.Y);
int rect_width = rect.Width;
int rect_height = rect.Height;

二、计算两点的距离

使用勾股定理计算两个坐标点的距离(在这个特定情况下是对角线长度)。

使用如下计算方式:

(1)勾股定理

在直角三角形中,直角边的平方和等于斜边(对角线)的平方:

45a2622db38c45a1b4f209f6dfcdfbdc.png

其中:

  • c 是斜边(这里表示从左上角到右下角的对角线长度),
  • a 和 b 分别是两条直角边(在这里,a 可以理解为水平方向上的差值 bottomRight.X - topLeft.X,而 b 为垂直方向上的差值 bottomRight.Y - topLeft.Y)。

(2)Math.Pow函数

原型:

public static double Pow (double x, double y);

解释:Math.Pow(底数x,指数y) , 函数用来求 x 的 y 次幂(次方)

(3)示例代码

// 定义矩形左上角和右下角的坐标
Point topLeft = new Point(0, 0);
Point bottomRight = new Point(5, 10); 

// 计算两点之间的距离(即对角线长度)
double distance = Math.Sqrt(Math.Pow(bottomRight.X - topLeft.X, 2) + Math.Pow(bottomRight.Y - topLeft.Y, 2));
Console.WriteLine("两点之间的距离 (对角线长度): " + distance);

 

 

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-11 18:46:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-11 18:46:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-11 18:46:01       82 阅读
  4. Python语言-面向对象

    2024-03-11 18:46:01       91 阅读

热门阅读

  1. HAproxy

    HAproxy

    2024-03-11 18:46:01      32 阅读
  2. uniapp聊天页面之消息滚动

    2024-03-11 18:46:01       47 阅读
  3. 大数据开发(Hadoop面试真题-卷九)

    2024-03-11 18:46:01       37 阅读
  4. LeetCode104 二叉树的最大深度

    2024-03-11 18:46:01       38 阅读
  5. 01.AJAX 概念和 axios 使用

    2024-03-11 18:46:01       40 阅读
  6. K8S Service

    2024-03-11 18:46:01       43 阅读
  7. Linux进程初步理解

    2024-03-11 18:46:01       43 阅读
  8. SpringBoot中事务

    2024-03-11 18:46:01       49 阅读
  9. Android10禁用wifi随机mac地址,固定mac地址

    2024-03-11 18:46:01       36 阅读
  10. 小蓝的钥匙(蓝桥杯错排)

    2024-03-11 18:46:01       44 阅读
  11. JDBC编程(数据库编程)

    2024-03-11 18:46:01       42 阅读
  12. 视觉信息处理和FPGA实现第二次作业

    2024-03-11 18:46:01       45 阅读
  13. 获取webshell的十种方法

    2024-03-11 18:46:01       37 阅读