两个CGRect比较的百分比

Reb*_*cca 0 comparison percentage ios cgrect

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

例子:

如果r1(0,0,150,150)r2(0,0,150,150)那么接收100%.

如果r1(0,0,150,150)r2(75,0,150,150)那么接收50%.

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

谢谢你的帮助 :-)

Sho*_*aib 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)) %");
Run Code Online (Sandbox Code Playgroud)

-

//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;
}
Run Code Online (Sandbox Code Playgroud)