ioscomparisonpercentagecgrect

Percentage for two CGRect comparaison


How can i get percentage for comparaison for two rects?

Examples:

if r1(0, 0, 150, 150) r2(0, 0, 150, 150) so receive 100%.

if r1(0, 0, 150, 150) r2(75, 0, 150, 150) so receive 50%.

I need some function that receive two rectangles and return percentage how much there are similar.. I need the percentage of the overlapping area of the two rectangles

Thanks for your help :-)


Solution

  • Try This;

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