将两个 CGPoint 转换为 CGRect
给定两个不同的 CGPoints,如何将它们转换为 CGRect?
示例:
CGPoint p1 = CGPointMake(0,10);
CGPoint p2 = CGPointMake(10,0);
如何将其转换为CGRect
?
How can I, given two different CGPoints
, turn them into an CGRect
?
Example:
CGPoint p1 = CGPointMake(0,10);
CGPoint p2 = CGPointMake(10,0);
How can I turn this into a CGRect
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这将采用两个任意点并为您提供以它们为对角的 CGRect。
较小的 x 值与较小的 y 值配对将始终是矩形的原点(前两个参数)。 x 值之间的差的绝对值为宽度,y 值之间的差的绝对值为高度。
This will take two arbitrary points and give you the CGRect that has them as opposite corners.
The smaller x value paired with the smaller y value will always be the origin of the rect (first two arguments). The absolute value of the difference between x values will be the width, and between y values the height.
对肯的答案稍作修改。让 CGGeometry 为您“标准化”矩形。
<代码>
CGRect 矩形 = CGRectStandardize(CGRectMake(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y));
A slight modification of Ken's answer. Let CGGeometry "standardize" the rect for you.
CGRect rect = CGRectStandardize(CGRectMake(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y));
快速扩展:
Swift extension:
假设 p1 是原点,另一个点是矩形的对角,您可以这样做:
Assuming p1 is the origin and the other point is the opposite corner of a rectangle, you could do this:
该函数接受任意数量的 CGPoints 并返回最小的 CGRect。
This function takes any number of CGPoints and gives you the smallest CGRect back.
如果两个点在一条线上,这将返回宽度或高度为 0 的矩形
This will return a rect of width or height 0 if the two points are on a line