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

 

 

  • 12
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值