两个CGRect比较的百分比

时间:2015-07-28 07:43:24

标签: ios comparison percentage cgrect

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

示例:

如果r1(0,0,150,150)r2(0,0,150,150)那么收到100%。

如果r1(0,0,150,150)r2(75,0,150,150)如此接受50%。

我需要一些函数来接收两个矩形并返回有多少相似的百分比.. 我需要两个矩形的重叠区域的百分比

感谢您的帮助: - )

2 个答案:

答案 0 :(得分:6)

试试这个;

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

答案 1 :(得分:0)

提出的解决方案无法处理其中一个矩形与另一个矩形重叠的情况。我添加了这种情况,并重构了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)