I'm trying to generate an astroid (Not asteroid) graphic similar to this:
This graphic output is generated on a 400x400 DrawingPanel. And the math is based on making curves from straight lines. However, I'm having a problem with my x,y coordinates. instead of making the astroid, I'm generating this:
Here is the code:
import java.awt.*;
public class GraphicsProject
{
//main method
public static void main (String[]args){
//Initialize the variable
//The Window is 400 x 400 pixels in size
DrawingPanel panel = new DrawingPanel (400,400);
Graphics g = panel.getGraphics();
drawAstroid(g,0,0, 400);
}
public static void drawAstroid(Graphics g, int x, int y, int size){
int scale = size/40;
int x1, x2,x3, x4, y1, y2, y3, y4;
y1 = y;
y2 = y + size;
y3 = y + 1/2 * size;
y4 = y + 1/2 * size;
x1 = x + 1/2 * size;
x2 = x + 1/2 * size;
x3 = x + 1/2 * size;
x4 = x + 1/2 * size;
for (int i = 0; i < 21; i++ ){
//Draws Upper Left
g.drawLine(x4 - scale * i, y4, x1, y1 + scale * i);
//Draws Upper Right
g.drawLine(x4 + scale * i, y4, x2, y2 - scale * i);
//Draws Lower Left
g.drawLine(x3 - scale * i, y3, x4, y4 + scale * i);
//Draws Lower Right
g.drawLine(x3 + scale * i, y3, x2, y2 - scale * i);
}
}
}
Any insight into how to resolve this would be appreciated.
Related
I have to draw a ring using lines (drawLine) in Java that should look like the attached picture. We are provided with the classDrawingPanel that can be found here.
I've made a regular circle using lines, but I'm unsure how to get the ring shape. I'm new to programming and this is my first post, so apologies if I've missed something important.
This is my code so far:
public static int panelSize = 400;
public static void drawCircle()
{
double radius = 200;
int x2 = 200;
int y2 = 200;
DrawingPanel dp = new DrawingPanel(panelSize, panelSize);
dp.setBackground(Color.CYAN);
Graphics dpGraphics = dp.getGraphics();
dpGraphics.setColor(Color.RED);
for (int circle = 0; circle <= 360; circle++)
{
int x = (int)(x2 + Math.sin(circle * (Math.PI / 180)) * radius);
int y = (int)(y2 + Math.cos (circle * (Math.PI / 180)) * radius);
dpGraphics.drawLine(x, y, x2, y2);
}
}
This is what the final result should look like:
Such a figure can be drawn by drawing a line from one point to a point farther away on the circle, passing the starting point several times.
This is what I came up with:
// Radius
int radius = 200;
// center of the circle
int centerX = 300, centerY = 300;
// The number of edges. Set to 5 for a pentagram
int mod = 136;
// The number of "points" to skip - set to 2 for a pentagram
int skip = 45;
// Precalculated multipier for sin/cos
double multi = skip * 2.0 * Math.PI / mod;
// First point, calculated by hand
int x1 = centerX; // sin(0) = 0
int y1 = centerY + radius; // cos(0) == 1
for (int circle = 1; circle <= mod; circle++)
{
// Calculate the end point of the line.
int x2 = (int) (centerX + radius * Math.sin(circle * multi));
int y2 = (int) (centerY + radius * Math.cos(circle * multi));
dpGraphics.drawLine(x1, y1, x2, y2);
// Next start point for the line is the current end point
x1 = x2;
y1 = y2;
}
The result looks like this:
I need to cover some polygon with rectangles here's an example :
The black figure in a black square is the polygon that i need to cover with those green rectangles but i need to do it more efficiently that just make a net like i did. Because as you can see there can be place more green rectangles if i moved them.
Rectangles inside are fixed size(just not as big as polygon it self), one for all like in the picture, they can be places vertically and horizontally, i want to fill the polygon as much as it can fit it inside of it, this polygon is just for example, there can be different polygons with holes in them for example that black small square is a hole.
module = rectangle
private void coverWithModules(Graphics g, int[] xpoints, int[] ypoints) {
Polygon module;
int x1, x2, x3, x4, y1, y2, y3, y4;
int moduleRowNumber = 0;
int totalRows = (getMax(ypoints) / moduleHeight);
while (moduleRowNumber < totalRows) {
// first module
x1 = getMin(xpoints);
y1 = getMin(ypoints) + distance * moduleRowNumber + moduleHeight
* moduleRowNumber;
x2 = x1 + moduleWidth;
y2 = y1;
x3 = x1 + moduleWidth;
y3 = y1 + moduleHeight;
x4 = x1;
y4 = y1 + moduleHeight;
int[] x = { x1, x2, x3, x4 };
int[] y = { y1, y2, y3, y4 };
module = new Polygon();
// check if point are inside the polygon
checkModulePlacement(g, x, y, module);
// placing modules in a row
while (x1 < getMax(xpoints)) {
x1 = x2 + distance;
y1 = getMin(ypoints) + distance * moduleRowNumber
+ moduleHeight * moduleRowNumber;
x2 = x1 + moduleWidth;
y2 = y1;
x3 = x1 + moduleWidth;
y3 = y1 + moduleHeight;
x4 = x1;
y4 = y1 + moduleHeight;
int[] xx = { x1, x2, x3, x4 };
int[] yy = { y1, y2, y3, y4 };
module = new Polygon();
checkModulePlacement(g, xx, yy, module);
}
moduleRowNumber++;
}
}
private void checkModulePlacement(Graphics g, int[] x, int[] y, Polygon module) {
boolean pointInside = true;
boolean pointOnObstraction = true;
for (int i = 0; i < x.length; i++) {
if (pointInside) {
pointInside = roof.contains(x[i], y[i]);
}
module.addPoint(x[i], y[i]);
}
pointOnObstraction = checkForObstractions(module);
g.setColor(Color.GREEN);
if (pointInside == true && pointOnObstraction == false ) {
g.drawPolygon(module);
}
}
I was looking for something and i have found Something like this maybe there is more stuff like this ?
I don't know where to search for such info. What should i look up to get what i need ? Maybe there is some kind of library for this kind of things ?
I'm trying to draw to filled circles, centered at random locations, with a line connecting the circles. The distance between the to centers is displayed on the line and whenever your resize the frame, the circles are redisplayed in new random locations.
I'm stuck in how to display the distance?
Any help is appreciated and thx for advance.
This's the code (what i managed to do):
public class Test extends JFrame {
public Test() {
add(new LineConnectingTheTwoCircles());
}
// Panel class
class LineConnectingTheTwoCircles extends JPanel {
//Default constructor
LineConnectingTheTwoCircles() {
}
/* Override paintComponent (getting access to the panel's Graphics
class) */
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int radius = 15;
// getting coordinates of circle 1
int x1 = (int) (Math.random() * (getWidth()));
int y1 = (int) (Math.random() * (getHeight()));
// getting coordinates of circle 2
int x2 = (int) (Math.random() * (getWidth()));
int y2 = (int) (Math.random() * (getWidth()));
// Setting color and drawing a filled circles (1 & 2)
g.setColor(Color.BLUE);
g.fillOval(x1 - radius, y1 - radius, 2 * radius, 2 * radius);
g.drawString("1", x1 - 25, y1);
g.setColor(Color.RED);
g.fillOval(x2 - radius, y2 - radius, 2 * radius, 2 * radius);
g.drawString("2", x2 - 25, y2);
connectingTheTwoCircles(g, x1, y1, x2, y2);
}
// Connecting the two circles from the center
private void connectingTheTwoCircles(Graphics g, int x1, int y1,
int x2, int y2) {
//Distance between the circles centered
double D = Math.sqrt((Math.pow((y2 - y1), 2))
+ (Math.pow((x2 - x1), 2)));
//Getting the coordinates for the line l
int x11 = x1;
int y11 = y1;
int x21 = x2;
int y21 = y2;
g.setColor(Color.BLACK);
g.drawLine(x11, y11, x21, y21);
}
public double getDistance(double x1, double y1, double x2, double y2) {
return Math.sqrt((Math.pow((y2 - y1), 2))
+ (Math.pow((x2 - x1), 2)));
}
}
public static void main(String[] args) {
// Frame declaration
Test frame = new Test();
/*
* Invoking some methods, to set a title on the title bar, to specifier
* the size of the frame to centre it on the screen, to tell the program
* to terminate when the frame is closed and finally to display it
*/
frame.setTitle("This is a test");
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Try next code draws distance at line center
double distance = getDistance(x11, y11, x21, y21);
g.drawString(distance+" ",
x11> x21 ? x21 + (x11-x21)/2 : x11 + (x21 - x11)/2 ,
y11> y21 ? y21 + (y11-y21)/2 : y11 + (y21 - y11)/2 );
My program contains main shapes i.e square, rect, circle they work good ( for x2,y2 in those shapes I used absolute values e.g square( x, y, 5, 5) ), but when working with triangle shape,
Triangles in my program glitches.
below is the code of my program modules,
if (vehicleStyle.getVehicleShape().equals(VehicleShape.TRIANGLE)) {
processingVisualizer
.fill(vehicleStyle.getColor().red,
vehicleStyle.getColor().green,
vehicleStyle.getColor().blue);
processingVisualizer.strokeWeight(1 * vehicleSize);
//System.out.println(x + "-" + y);
//## to place face toward movement direction
/*
* -----<|----
* | |
* \/ /\
* | |
* -----|>----
*/
float x2, y2, x3, y3;
if (x == 100) {
System.out.println( "x==100");
x2 = x - 5;
y2 = y + 5;
x3 = x + 5;
y3 = y + 5;
processingVisualizer.triangle(x, y, x2, y2, x3, y3);
} else if (x == 20) {
System.out.println( "x==20");
x2 = x - 2;
y2 = y - 2;
x3 = x + 2;
y3 = y - 2;
processingVisualizer.triangle(x, y, x2, y2, x3, y3);
} else if (y == 100) {
System.out.println( "y ==100");
x2 = x - 2;
y2 = y - 2;
x3 = x - 2;
y3 = y + 2;
processingVisualizer.triangle(x, y, x2, y2, x3, y3);
} else if (y == 20) {
System.out.println( "y ==20");
x2 = x+5;//x - 2;
y2 = y-5;
x3 = x+5 ;//- 2;
y3 = y+5;
processingVisualizer.triangle(x, y, x2, y2, x3, y3);
}
}
processingVisualizer.strokeWeight(1);
}
Can't test your code, but my assumption is the "glitch" happens because you are rendering a triangle only when your 4 conditions are met. You should update the triangle's corner positions based on your conditions if you like, but render the triangle all time, even when the positions are out of date:
if (vehicleStyle.getVehicleShape().equals(VehicleShape.TRIANGLE)) {
processingVisualizer
.fill(vehicleStyle.getColor().red,
vehicleStyle.getColor().green,
vehicleStyle.getColor().blue);
processingVisualizer.strokeWeight(1 * vehicleSize);
//System.out.println(x + "-" + y);
//## to place face toward movement direction
/*
* -----<|----
* | |
* \/ /\
* | |
* -----|>----
*/
float x2, y2, x3, y3;
if (x == 100) {
System.out.println( "x==100");
x2 = x - 5;
y2 = y + 5;
x3 = x + 5;
y3 = y + 5;
} else if (x == 20) {
System.out.println( "x==20");
x2 = x - 2;
y2 = y - 2;
x3 = x + 2;
y3 = y - 2;
} else if (y == 100) {
System.out.println( "y ==100");
x2 = x - 2;
y2 = y - 2;
x3 = x - 2;
y3 = y + 2;
} else if (y == 20) {
System.out.println( "y ==20");
x2 = x+5;//x - 2;
y2 = y-5;
x3 = x+5 ;//- 2;
y3 = y+5;
}
processingVisualizer.triangle(x, y, x2, y2, x3, y3);
}
processingVisualizer.strokeWeight(1);
}
Also, you can easily compute the direction of motion, if you store the previous position, using the arc tangent function (atan2()):
float angle = atan2(currentY-previousY,currentX-previousX);
Here's a quick example:
float cx,cy,px,py;//current x,y, previous x,y
float len = 15;
void setup(){
size(200,200);
background(255);
}
void draw(){
//update position - chase mouse with a bit of easing
cx -= (cx - mouseX) * .035;
cy -= (cy - mouseY) * .035;
//find direction of movement based on the current position
float angle = atan2(cy-py,cx-px);
//store previous position
px = cx;
py = cy;
//render
fill(255,10);noStroke();
rect(0,0,width,height);
fill(127,32);stroke(0);
pushMatrix();
translate(cx,cy);
pushMatrix();
rotate(angle);
triangle(len,0,-len,-len,-len,len);
line(0,0,len,0);
popMatrix();
popMatrix();
}
I need a function which takes a line (known by its coordinates)
and return a line with same angle, but limited to certain length.
My code gives correct values only when the line is turned 'right'
(proven only empirically, sorry).
Am I missing something?
public static double getAngleOfLine(int x1, int y1, int x2, int y2) {
double opposite = y2 - y1;
double adjacent = x2 - x1;
if (adjacent == Double.NaN) {
return 0;
}
return Math.atan(opposite / adjacent);
}
// returns newly calculated destX and destY values as int array
public static int[] getLengthLimitedLine(int startX, int startY,
int destX, int destY, int lengthLimit) {
double angle = getAngleOfLine(startX, startY, destX, destY);
return new int[]{
(int) (Math.cos(angle) * lengthLimit) + startX,
(int) (Math.sin(angle) * lengthLimit) + startY
};
}
BTW: I know that returning arrays in Java is stupid,
but it's just for the example.
It would be easier to just treat it as a vector. Normalize it by dividing my its magnitude then multiply by a factor of the desired length.
In your example, however, try Math.atan2.
In Python because I don't have a Java compiler handy:
import math
def getLengthLimitedLine(x1, y1, x2, y2, lengthLimit):
length = math.sqrt((x2-x1)**2 + (y2-y1)**2)
if length > lengthLimit:
shrink_factor = lengthLimit / length
x2 = x1 + (x2-x1) * shrink_factor
y2 = y1 + (y2-y1) * shrink_factor
return x2, y2
print getLengthLimitedLine(10, 20, 25, -5, 12)
# Prints (16.17, 9.71) which looks right to me 8-)
It's an easy problem if you understand something about vectors.
Given two points (x1, y1) and (x2, y2), you can calculate the vector from point 1 to 2:
v12 = (x2-x1)i + (y2-y2)j
where i and j are unit vectors in the x and y directions.
You can calculate the magnitude of v by taking the square root of the sum of squares of the components:
v = sqrt((x2-x2)^2 + (y2-y1)^2)
The unit vector from point 1 to point 2 equals v12 divided by its magnitude.
Given that, you can calculate the point along the unit vector that's the desired distance away by multiply the unit vector times the length and adding that to point 1.
Encapsulate Line in a class, add a unit method and a scale method.
public class Line {
private float x;
private float y;
public Line(float x1, float x2, float y1, float y2) {
this(x2 - x1, y2 - y1);
}
public Line(float x, float y) {
this.x = x;
this.y = y;
}
public float getLength() {
return (float) Math.sqrt((x * x) + (y * y));
}
public Line unit() {
return scale(1 / getLength());
}
public Line scale(float scale) {
return new Line(x * scale, y * scale);
}
}
Now you can get a line of arbitrary length l by calling
Line result = new Line(x1, x2, y1, y2).unit().scale(l);
No need to use trig, which can have some nasty edge cases. Just use similar triangles:
public static int[] getLengthLimitedLine(int startX, int startY,
int destX, int destY, int lengthLimit)
{
int deltaX = destX - startX;
int deltaY = destY - startY;
int lengthSquared = deltaX * deltaX + deltaY * deltaY;
// already short enough
if(lengthSquared <= lengthLimit * lengthLimit)
return new int[]{destX, destY};
double length = Math.sqrt(lengthSquared);
double newDeltaX = deltaX * lengthLimit / length;
double newDeltaY = deltaY * lengthLimit / length;
return new int[]{(int)(startX + newDeltaX), (int)(startY + newDeltaY)};
}
Just use the Pythagorean theorem, like so:
public static int[] getLengthLimitedLine(int start[], int dest[], int lengthLimit) {
int xlen = dest[0] - start[0]
int ylen = dest[1] - start[1]
double length = Math.sqrt(xlen * xlen + ylen * ylen)
if (length > lengthLimit) {
return new int[] {start[0], start[1],
start[0] + xlen / lengthLimit,
start[1] + ylen / lengthLimit}
} else {
return new int[] {start[0], start[1], dest[0], dest[1];}
}
}