Drawing rectangles from center of given coordinate - java

I made a program where user enters number of rectangles to be drawn and coordinates at which the rectangles are drawn. My rectangles are currently drawn like this:
and I want to achieve this:
This is the code I use to draw the rectangles:
int povecaj_kvadrat=0;
for(int x=0;x<broj_kvadrata;x++) {
Rectangle2D.Float kvadrat=new Rectangle2D.Float(brojevi_koordinate[0],brojevi_koordinate[1],50+povecaj_kvadrat,50+povecaj_kvadrat);
ploca.draw((kvadrat));
povecaj_kvadrat=povecaj_kvadrat+15;
}
}
How do I set the coordinates of the rectangles so that they are drawn like in the second image?

You will have to take into account the additional size of each Rectangle, along with its position within the loop to compute the correct coordinates of each rectangle.
The additional size has been moved as a variable (diffSize), so that your loop can use its value.
The difference in coordinates between two iterations will be half this diff size, multiplied by the inverse of the position in the loop, because the lower the increment (x) and the Rectangle size, the bigger the coordinates .
int gap = 0;
int maxNumber = 3;
int diffSize = 20;
int[] coordinates = { 10, 10 };
for (int x = 0; x <= maxNumber; x++) {
Rectangle2D.Float rectangle = new Rectangle2D.Float(
coordinates[0] + ((diffSize / 2) * (maxNumber - x)),
coordinates[1] + ((diffSize / 2) * (maxNumber - x)),
50 + gap, 50 + gap);
g2d.draw((rectangle));
gap = gap + diffSize;
}
Note that I am unsure of the correct behaviour if diffSize is odd (because (diffSize / 2) will be rounded down to the nearest int value), so I would keep an even value for diffSize.

Related

How to make circles in a panel not touch the borders? (Java Graphics)

I would like to create circles with a random diameter, position and color in a panel with the Graphics class in Java. It works fine, however I have the problem that often circles touch or overlap the border.
How can I make the circles fully stay within the panel?
Thanks in advance!
This is the code I use for creating the circles:
amount = rnd.nextInt(10);
for (int i = 0; i < amount; i++){
x = (50 + rnd.nextInt(panel.getWidth() - 50 + 1)) - 50;
y = (50 + rnd.nextInt(panel.getHeight() - 50 + 1)) - 50;
diameter = (rnd.nextInt(100));
gr.setColor(new Color(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
gr.fillOval(x, y, diameter, diameter);
gr.drawString("" + (panel.getHeight() - y), x, y);
}
x = (50 + rnd.nextInt(panel.getWidth() - 50 + 1)) - 50;
y = (50 + rnd.nextInt(panel.getHeight() - 50 + 1)) - 50;
diameter = (rnd.nextInt(100));
How can you calculation the x/y position if you don't know what the diameter of the circle is going to be?
First you need to calculate the diameter. Then you need to use the diameter to make sure the x/y plus the diameter is less than the width of the panel.
I don't understand the point of adding 50 and then subtracting 50. I would think the random number should be the width minus the diameter.

Fill a shape with points

I try to draw a leaf looking thing on the screen, and try to fill it with a color. It's like drawing a circle, the difference is, that it's only 270 degrees, and the radius starts from 0 to 100. I first draw the left side, and on each degree I fill the inside. At the end I draw the right side.
Here is to code, maybe it's easier to understand:
canvas = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);
Color black = new Color(0,0,0);
Color green = new Color(0,130,0);
double j = 0.0; // radius
double max = 100.0; // max radius
for (int i = 0; i < 135; i++) { // left side (270 degree / 2)
j += max / 135.0;
// x, y coordinate
int x = (int)(Math.cos(Math.toRadians(i)) * j);
int y = (int)(Math.sin(Math.toRadians(i)) * j);
// draw a circle like thing with radius j
for (int l = i; l < 135 + (135 - i); l++) {
int ix = (int)(Math.cos(Math.toRadians(l)) * j);
int iy = (int)(Math.sin(Math.toRadians(l)) * j);
canvas.setRGB(ix + 256, iy + 256, green.getRGB());
}
canvas.setRGB(x + 256, y + 256, black.getRGB());
}
// draw the right side
for (int i = 135; i < 270; i++) {
j -= max / 135.0;
int x = (int)(Math.cos(Math.toRadians(i)) * j);
int y = (int)(Math.sin(Math.toRadians(i)) * j);
canvas.setRGB(x + 256, y + 256, black.getRGB());
}
This is the result:
As you can see, where the radius is bigger, the leaf is not filled completely.
If I change i to 1350, then divide it with 10 where I calculate x, y, then it's filled, but it's much slower. Is there a better way to properly fill my shape?
Later I also would like to fill my shape with a gradient, so from green to a darker green, then back to green. With my method this is easy, but super slow.
Thanks in advance!
I think that for you the best solution is to use a flood fill algorithm, it's easy to implement in Java and efficient in your case, like you have a simple shape.
Here is a wikipedia article that is really complet : http://en.wikipedia.org/wiki/Flood_fill
Here is a simple suggestion: Instead of drawing the leaf, just put the points that create the outline into an array. The array should run from xMin (smallest X coordiate of the leaf outline) to xMax. Each element is two ints: yMin and yMax.
After rendering all the points, you can just draw vertical lines to fill the space between yMin/yMax for each X coordinate.
If you have gaps in the array, fill them by interpolating between the neighboring points.
An alternative would be to sort the points clockwise or counter-clockwise and use them as the outline for a polygon.

Canvas for drawing is a circle; random dots within canvas

I'm practicing for an exam, and I'm doing one of the practice problems. I have a method that takes two arguments: one for the radius of a circle, and one for the number of dots to place within that circle. The method is below:
private void drawDots(int radius, int numDots){
double ycord;
double xcord;
for(int q = 0; q < numDots; q++){
ycord = -radius + random()*(radius+radius+1);
xcord = pow((pow(radius,2)-pow(ycord,2)),0.5);
turt.moveTo(xcord,ycord);
turt.penDown();
turt.forward(0);
turt.penUp();
}
}
turt is an object I'm using to draw with, and penDown()/penUp() is placing and removing the object from the canvas respectively.
I'm trying to define the x-coordinate and y-coordinate of the turt object to stay within a radius. Say the radius is 100, and the number of dots is 200, how do I keep the object within that radius?
The question states that:
"To constain the dots to a circle of radius r, a random y-coord in the interval -r, r is chosen. To x-coord is then randomly chosen in the interval -b, b, where b = sqrt(r^2 - y^2)."
I'm just not sure how to make sense of this math. The code above was my best attempt, but the output is strange.
Here is my failed output:
The distance from the center (0,0) to a dot must be less than the radius of the circle, r. The distance can be expressed as sqrt(x² + y²). Therefore, if you choose your y coordinate randomly between [-r, r], you just have to make sure that your x coordinate respects the previous equation, hence your math.
Demonstration
sqrt(x² + y²) < r
x² + y² < r²
x² < r² - y²
x < sqrt(r² - y²)
#
Your algorithm should be as follows. Once you chose the y coordinate, you can randomly choose x as long as it respects the distance constraint.
private void drawDots(int radius, int numDots){
double y;
double x;
double xMax;
for (int q = 0; q < numDots; q++){
// y is chosen randomly
y = -radius + random() * (radius + radius + 1);
// x must respect x² + y² < r²
xMax = pow((pow(radius,2)-pow(ycord,2)), 0.5);
x = random() * 2 * xMax - xMax;
turt.moveTo(x, y);
turt.penDown();
turt.forward(0);
turt.penUp();
}
}
Take a look at the documentation for random, you will see by default it produces a number between 0 and 1.
Basically this means that the expression you are looking for is:
ycord=-radius+random()*(radius*2);
This gives you a point on the y axis between -radius and radius (consider if the random() returns 0 you get -radius, it it returns 1 you get -radius+(2*radius())=radius.
You calculation for the x co-ordinate is correct but it gives you the x coordinate point on the circle (lets call it b). I suspect you want to use a new random to select an x co-ordinate between b and -b.
At present you are drawing points on the circle, not inside it. That is because you are not following the guideline correctly.
b = pow((pow(radius,2)-pow(ycord,2)),0.5); // this should be b
xcord = -b + random()*(b+b);

Java: Object moving on a path, ignores certain coordinates. How to fix?

I have a circle that moves from point A to a random point B. When the object nears point B, a new random target location gets chosen. If the circle is moving parallel to the X-axis or Y-axis the object goes through all the pixels in the way and leaves a solid trace. But if the circle moves diagonally, it skips pixels and shakes slightly, making the animation not smooth and leaves a trace with unpainted pixels.
My algorithm is:
calculate the X and Y distances
check if the circle is near
if so, choose the new destination
if 2. is true, find the real distance using Pythagoras' theorem
if 2. is true, calculate the X and Y speed (the change of the coordinates)
set the new coordinates (no matter if 2. is true or not)
And here is the code:
public void move ()//движение
{
//finds the X and Y distance to the destination
int triangleX = nextLocationX - coorX;
int triangleY = nextLocationY - coorY;
//if too near the coordinates of the destination changes
if (Math.abs(triangleX) <= Math.abs(speedX) || Math.abs(triangleY) <= Math.abs(speedY))//setting the new target
{
//setting the new destinatio
int randInt;
for (;;)//I don't want the the new destination to be that same spot
{
randInt= randGen.nextInt(appletX);
if (randInt != nextLocationX)
{
nextLocationX = randInt + radius;
break;
}
}
for (;;)
{
randInt = randGen.nextInt(appletY);
if (randInt != nextLocationY)
{
nextLocationY = randInt + radius;
break;
}
}
//calculating the change of the circle's X and Y coordinates
triangleX = nextLocationX - coorX;
triangleY = nextLocationY - coorY;
speedX = ((double)(speed * triangleX) / (Math.sqrt (Math.pow(triangleX, 2) + Math.pow(triangleY, 2))));
speedY = ((double)(speed * triangleY) / (Math.sqrt (Math.pow(triangleX, 2) + Math.pow(triangleY, 2))));
}
//the realCoor variables are from type double
//they are the exact coordinates of the circle
//If I only use integers, the circle almost
//never reaches it's destination
//unless the change of the coordinates gets calculated
//after every time they change
realCoorX = realCoorX + speedX;
realCoorY = realCoorY + speedY;
coorX = (int)Math.round(realCoorX);
coorY = (int)Math.round(realCoorY);
}
I suspect that the problem is in the calculation of the change of the coordinates.
For me this sounds like a Aliasing problem. You would have the same problem if you draw(!) a line that is not aligned with the coordinate axis. As you know, i.e. diagonal lines need "half filled" pixels to look smooth.
Solution for you would be (depending on the technology for rendering) to use floating point position calculation.

How to Draw a simple GUI Histogram

I need to draw a simple histogram for a project I'm working on that needs to look this...
I know there is got to be some simple for loop to run on my H[] array which consists of how many pixels belong to each gray scale value... so in H[] we have lets say "10 pixels in gray scale value 1" so at 1 there would be a line of length 10 going vertically next to my image...
if anyone could offer their help, I would greatly appreciate it!
Thanks.
wrote this but its too big and upside down and angled for some reason.
if (H != null) {
int width = getWidth();
int height = getHeight();
int HhPos = (width - (width/2));
int HvPos = (height - (height));
for(int i = 0 ; i <255 ; i++){
g.drawRect(i+HhPos, i+HvPos, 1, H[i]);
}
As Gilbert said, you need to normalize you values, to determine the maximum range or ceiling.
From this you can then determine the percentage of a given value compared to the maximum and then plot it on the graph, based on the available height.
(Taken from the previous answer to this question)
// Determine the maximum vertical value...
int maxValue = 0;
for (Integer key : mapHistory.keySet()) {
int value = mapHistory.get(key);
maxValue = Math.max(maxValue, value);
}
int xPos = xOffset;
for (Integer key : mapHistory.keySet()) {
int value = mapHistory.get(key);
// Calculate the percentage that the given value uses compared to that of the
// maximum value
float percentage = (float)value / (float)maxValue;
// Calculate the line height based on the available vertical space...
int barHeight = Math.round(percentage * height);
g2d.setColor(new Color(key, key, key));
int yPos = height + yOffset - barHeight;
Rectangle2D bar = new Rectangle2D.Float(xPos, yPos, barWidth, barHeight);
g2d.fill(bar);
g2d.setColor(Color.DARK_GRAY);
g2d.draw(bar);
xPos += barWidth;
}
Now in the previous example, I used a Map to to store the values, but it should relativly easy to replace that with your data array...
for (Integer key : mapHistory.keySet()) would become for (int key : H)
Also, with Graphics.drawLine, it is drawing a line from one point to another, not one point to a width/height value (like say Graphics.drawRectangle)
You're plotting points that have an x and y value. You're drawing a histogram that has a width and height in pixels.
For example, let's say your histogram is 500 pixels in width, and 300 pixels in height.
You go through your data points once, looking for the minimum x, minimum y, maximum x, and maximum y.
Assuming we're plotting Y points (the X axis is the width), you subtract the minimum x from the maximum x. Divide 500 pixels (the width) by the difference, and you get the number of pixels per x value. This number can be greater than one, so you have more than one pixel per x value. This number can be less than one, so you have more data values than pixels.
width pixels per value = width of histogram in pixels / difference in X points
You do the same for the Y axis. Calculate the pixels per y value.
height pixels per value = height of histogram in pixels / difference in y points
Now, you go through your data points a second time. For each data point, you calculate the width and height in pixels from the x and y value of the data point. You use the number of pixels per value for both the width and the height to make the conversion.
width = x value * width pixels per value
height = y value * height pixels per value
You use the Java Graphics drawLine or drawRect method to draw the line or bar in your histogram. Just remember that the Y dimension in Java graphics goes down, rather than up like in your histograph. You'll have to take this into account when you're drawing.

Categories