两个CGRect比较的百分比

问题描述 投票:0回答:3

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

示例:

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

如果 r1(0, 0, 150, 150) r2(75, 0, 150, 150) 那么获得 50%。

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

感谢您的帮助:-)

ios comparison percentage cgrect
3个回答
10
投票

试试这个;

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

3
投票

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

0
投票

也许这会派上用场

func rectIntersectionInPerc(r1: CGRect, r2: CGRect) -> CGFloat {
   if r1.intersects(r2) {
      let interRect: CGRect = r1.intersection(r2)
      let intersectionArea = interRect.width * interRect.height
      let rectArea = r1.width * r1.height
      return (intersectionArea / rectArea) * 100.0
   }

   return 0
}
© www.soinside.com 2019 - 2024. All rights reserved.