1. 程式人生 > >螢幕座標系獲取兩個矩形面積及重疊面積,重疊面積比率的java程式碼

螢幕座標系獲取兩個矩形面積及重疊面積,重疊面積比率的java程式碼


import java.math.*;

/*
* x,y為矩形左上角座標,width為寬,height為高
*
*/

public class MyRectangle
{
	public int x;
	public int y;
	public int width;
	public int height;
	
	public MyRectangle()
	{
		
	}
	
	public MyRectangle(int x,int y,int width,int height)
	{
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}
	
	public int getArea()
	{
		return this.height * this.width;
	}
	
	public static int getOverLappingArea(MyRectangle a,MyRectangle b)
	{
		int overLappingArea = 0;
		
		int startX = Math.min(a.x,b.x);
		int endX = Math.max(a.x + a.width, b.x + b.width);
		int overLappingWidth = a.width + b.width - (endX - startX);
		
		int startY = Math.min(a.y, b.y);
		int endY = Math.max(a.y + a.height, b.y + b.height);
		int overLappingHeight = a.height + b.height - (endY - startY);
		
		if(overLappingWidth <= 0 || overLappingHeight <= 0)
		{
			overLappingArea = 0;
		}
		else
		{
			overLappingArea = overLappingWidth * overLappingHeight;
		}
		return overLappingArea;
		
	}
	
	public static double getOverLappingRate(MyRectangle a,MyRectangle b)
	{
		double overLappingRate = 0.0;
		int overLappingArea = getOverLappingArea(a,b);
		if(overLappingArea == 0)
		{
			overLappingRate = 0.0;
		}
		else
		{
			int areaA = a.getArea();
			int areaB = b.getArea();
			overLappingRate = (double)overLappingArea / (double)(areaA + areaB - overLappingArea);
		}
		return overLappingRate;	
	}
}