【问题标题】:Percentage for two CGRect comparaison两个 CGRect 比较的百分比
【发布时间】:2015-07-28 07:43:24
【问题描述】:

如何获得两个矩形的比较百分比?

例子:

如果 r1(0, 0, 150, 150) r2(0, 0, 150, 150) 所以收到 100%。

如果 r1(0, 0, 150, 150) r2(75, 0, 150, 150) 所以收到 50%。

我需要一些函数来接收两个矩形并返回相似的百分比.. 我需要两个矩形重叠面积的百分比

感谢您的帮助:-)

【问题讨论】:

  • 我猜你可以创建这样的方法。
  • 这不是您想要的,但很有用。 BOOL isIntersecting = CGRectIntersectsRect(rect1, rect2);

标签: ios comparison percentage cgrect


【解决方案1】:

试试这个;

var r1:CGRect = CGRect(x: 0, y: 0, width: 150, height: 150);
var r2:CGRect = CGRect(x: 75, y: 0, width: 150, height: 150);
//--
var per = rectIntersectionInPerc(r1, r2: r2);
NSLog("per : \(per)) %");

-

//Width and Height of both rects may be different
func rectIntersectionInPerc(r1:CGRect, r2:CGRect) -> CGFloat {
    if (r1.intersects(r2)) {

       //let interRect:CGRect = r1.rectByIntersecting(r2); //OLD
       let interRect:CGRect = r1.intersection(r2);

       return ((interRect.width * interRect.height) / (((r1.width * r1.height) + (r2.width * r2.height))/2.0) * 100.0)
    }
    return 0;
}

【讨论】:

  • 谢谢,但如果矩形的宽度和高度不同?
  • @Rebecca 查看不同宽度和高度矩形的更新功能。
  • 谢谢你我会检查这个:-)
  • rectByIntersecting 是什么?
  • 猜它是旧的 Swift:我相信现在是 intersection
【解决方案2】:

建议的解决方案不处理其中一个矩形与另一个重叠的情况。我添加了这个案例,并将 API 重构为更符合习惯。

extension CGRect {
    func intersectionPercentage(_ otherRect: CGRect) -> CGFloat {
        if !intersects(otherRect) { return 0 }
        let intersectionRect = intersection(otherRect)
        if intersectionRect == self || intersectionRect == otherRect { return 100 }
        let intersectionArea = intersectionRect.width * intersectionRect.height
        let area = width * height
        let otherRectArea = otherRect.width * otherRect.height
        let sumArea = area + otherRectArea
        let sumAreaNormalized = sumArea / 2.0
        return intersectionArea / sumAreaNormalized * 100.0
    }
}

可以这样使用:

let percentage = frame.intersectionPercentage(otherFrame)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2018-04-18
    • 2017-08-10
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    相关资源
    最近更新 更多