Bob J
Bob J

Reputation: 333

java, determine if circle is inside an area

Hi im new to programming and im trying to code an algorithm in java to determine if a circle is in a rectangular area

I have the radius of the circle and the point in the middle of it(the center)

|_____________________________________________________
|   
|  
|  
|                     circle
|   
|  
|  
|  
|(0,0)________________________________________________

the bottom left corner represent the coordinate (0,0)

this is what I have so far but I know I have an error somewhere which I can't find

if (mCenter.getmX() + mRadius > width || 
    mCenter.getmY() + mRadius > height ||
    mCenter.getmX() - mRadius < 0 ||
    mCenter.getmY() - mRadius < 0) {
        return false; //not inside area
    }  
else { return true; }

In this code mCenter is a Point with a x and y coordinate, mRadius is the circle radius and width and height are the width/height of the area

thanks

Upvotes: 0

Views: 221

Answers (1)

Jerry101
Jerry101

Reputation: 13467

You didn't say what the symptom is, but your helpful diagram above uses the ordinary mathematical coordinate system while your posted code uses awt.image.BufferedImage. Swing and most 2D computer graphics systems use a different coordinate system that's more convenient for laying out content in reading order.

Per GraphicsConfiguration#getDefaultTransform():

Coordinates in the coordinate space defined by the default AffineTransform for screen and printer devices have the origin in the upper left-hand corner of the target region of the device, with X coordinates increasing to the right and Y coordinates increasing downwards.

I think it's possible to set up a GraphicsConfiguration with a different transform. (I don't know how to do it.) Not so for awt.image.BufferedImage:

All BufferedImage objects have an upper left corner coordinate of (0, 0).

javax.swing.SwingUtilities has coordinate conversion methods.

P.S. Calling image.setRGB() for each pixel will be slow compared to passing the entire image into setRGB(int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize) or setData(Raster r). Usually a frame buffer is held in a 1-D array that's treated like a 2-D array, with scansize indicating the width of a scan line within this buffer.

Upvotes: 1

Related Questions