Rotating rectangle and adjust positon - java

I'm currently struggling with the rotation of some rectangles.
I have a rectangle which consists of 9 small rectangles.
http://i57.tinypic.com/msn8ue.jpg
Now I rotated the big rectangle accordingly with affine transformation, which worked pretty fine.
http://i61.tinypic.com/25phlqp.jpg
My problem is that i now need to move the rectangles, so that the top left position of each rectangle is at point x,y.
I don't know how to do that and I hope that you can help me out.
Thanks!
public class MainClass {
public static void main(String[] args) {
JFrame jf = new JFrame("Demo");
Container cp = jf.getContentPane();
MyCanvas tl = new MyCanvas();
cp.add(tl);
jf.setSize(800, 800);
jf.setVisible(true);
}
}
class MyCanvas extends JComponent {
private static final long serialVersionUID = 5703217428905757134L;
#Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int x = 400;
int y = 400;
int width = 100;
int height = 200;
final int OVERLAPPING_OUTLINE = 10;
Rectangle[] rect = new Rectangle[9];
rect[0] = new Rectangle(x + OVERLAPPING_OUTLINE, y + OVERLAPPING_OUTLINE, width - 2 * OVERLAPPING_OUTLINE, height - 2
* OVERLAPPING_OUTLINE);
rect[1] = new Rectangle(x - OVERLAPPING_OUTLINE, y - OVERLAPPING_OUTLINE, OVERLAPPING_OUTLINE * 2,
OVERLAPPING_OUTLINE * 2);
rect[2] = new Rectangle(x - OVERLAPPING_OUTLINE + width, y - OVERLAPPING_OUTLINE, OVERLAPPING_OUTLINE * 2,
OVERLAPPING_OUTLINE * 2);
rect[3] = new Rectangle(x - OVERLAPPING_OUTLINE, y + height - OVERLAPPING_OUTLINE, OVERLAPPING_OUTLINE * 2,
OVERLAPPING_OUTLINE * 2);
rect[4] = new Rectangle(x - OVERLAPPING_OUTLINE + width, y + height - OVERLAPPING_OUTLINE, OVERLAPPING_OUTLINE * 2,
OVERLAPPING_OUTLINE * 2);
rect[5] = new Rectangle(x - OVERLAPPING_OUTLINE, y + OVERLAPPING_OUTLINE, OVERLAPPING_OUTLINE * 2, height
- OVERLAPPING_OUTLINE * 2);
rect[6] = new Rectangle(x - OVERLAPPING_OUTLINE + width, y + OVERLAPPING_OUTLINE, OVERLAPPING_OUTLINE * 2, height
- OVERLAPPING_OUTLINE * 2);
rect[7] = new Rectangle(x + OVERLAPPING_OUTLINE, y - OVERLAPPING_OUTLINE, width - OVERLAPPING_OUTLINE * 2,
2 * OVERLAPPING_OUTLINE);
rect[8] = new Rectangle(x + OVERLAPPING_OUTLINE, y + height - OVERLAPPING_OUTLINE, width - OVERLAPPING_OUTLINE * 2,
2 * OVERLAPPING_OUTLINE);
for (Rectangle r : rect)
g2.draw(r);
g2.setColor(Color.RED);
AffineTransform af = new AffineTransform();
for (int i = 90; i < 360; i += 90) {
af.rotate(Math.toRadians(i), x - OVERLAPPING_OUTLINE, y - OVERLAPPING_OUTLINE);
for (Rectangle r : rect) {
Shape shape = af.createTransformedShape(r);
g2.draw(shape);
}
}
}
}

It looks like you need to use AffineTransform.translate(double tx, double ty).

Related

Drag-resizing rectangle with fixed aspect ratio northwest corner

I have a Java app where the user can crop a subimage from its original self. The crop area is selected by drawing a rectangle over the original image. The rectangle can then be resized diagonally. And so far, everything works!
The user also has an option to lock the aspect ratio of the rectangle to 4:3. I can achieve this simply by setting the width to w = h / 4 * 3;
However, when it comes to resizing with locked ratio, the rectangle behaves strangely and is no longer stationary when dragging from the northwest corner (see gif below). Had the same problem with southwest corner, but that could be fixed by instead setting height to h = w / 3 * 4; but I can't figure out how to do this mathematically for the northwest corner. I have provided a copy-pastable demo for experimentation:
public class CropDemo {
public static void main(String[] args) {
CropPanel cropPanel = new CropPanel();
cropPanel.setPreferredSize(new Dimension(640, 480));
JFrame jFrame = new JFrame("Crop Panel");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.getContentPane().add(cropPanel);
jFrame.setResizable(false);
jFrame.pack();
jFrame.setLocationRelativeTo(null);
jFrame.setVisible(true);
}
}
class CropPanel extends JPanel {
private static final long serialVersionUID = 1L;
private boolean fixedRatio = true;
private Rectangle rectangle;
private Point clickPoint;
private static final int HOVERING = 0;
private static final int MOVING = 1;
private static final int RESIZING = 2;
public CropPanel() {
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
MouseAdapter mouseHandler = new MouseAdapter() {
private Point startPoint = null;
#Override
public void mouseClicked(MouseEvent e) {
if (rectangle != null && getCursorState() == HOVERING) {
rectangle = null;
repaint();
}
}
#Override
public void mousePressed(MouseEvent e) {
clickPoint = e.getPoint();
startPoint = e.getPoint();
}
#Override
public void mouseMoved(MouseEvent e) {
if (rectangle != null) {
Point mouse = e.getPoint();
int width = rectangle.x + rectangle.width;
int height = rectangle.y + rectangle.height;
final int off = 5;
if (mouse.x > rectangle.x - off && mouse.x < width + off && mouse.y > rectangle.y - off
&& mouse.y < height + off) {
if (mouse.x <= rectangle.x + off && mouse.y >= height - off) {
setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
} else if (mouse.x >= width - off && mouse.y >= height - off) {
setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
} else if (mouse.x <= rectangle.x + off && mouse.y <= rectangle.y + off) {
setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR));
} else if (mouse.x >= width - off && mouse.y <= rectangle.y + off) {
setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR));
} else {
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
} else {
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (clickPoint != null) {
Point mouse = e.getPoint();
if (getCursorState() == MOVING) {
int dx = rectangle.x + mouse.x - clickPoint.x;
int dy = rectangle.y + mouse.y - clickPoint.y;
rectangle.setLocation(dx, dy);
clickPoint = e.getPoint();
} else if (getCursorState() == RESIZING) {
int dx = mouse.x - startPoint.x;
int dy = mouse.y - startPoint.y;
int height = rectangle.height;
int width = rectangle.width;
int x = 0;
int y = 0;
int w = 0;
int h = 0;
switch (getCursor().getType()) {
case Cursor.SW_RESIZE_CURSOR:
x = mouse.x + dx;
y = rectangle.y;
w = width - dx;
h = height + dy;
if (fixedRatio) {
h = w / 3 * 4;
}
break;
case Cursor.SE_RESIZE_CURSOR:
x = rectangle.x;
y = rectangle.y;
w = width + dx;
h = height + dy;
if (fixedRatio) {
w = h / 4 * 3;
}
break;
case Cursor.NW_RESIZE_CURSOR:
x = mouse.x + dx;
y = mouse.y + dy;
w = width - dx;
h = height - dy;
// This is where I'm lost
// something else needs to be done
if (fixedRatio) {
w = h / 4 * 3;
}
break;
case Cursor.NE_RESIZE_CURSOR:
x = rectangle.x;
y = mouse.y + dy;
w = width + dx;
h = height - dy;
if (fixedRatio) {
w = h / 4 * 3;
}
break;
}
rectangle.setBounds(x, y, w, h);
startPoint = mouse;
} else {
int x = Math.min(clickPoint.x, mouse.x);
int y = Math.min(clickPoint.y, mouse.y);
int w = Math.max(clickPoint.x - mouse.x, mouse.x - clickPoint.x);
int h = Math.max(clickPoint.y - mouse.y, mouse.y - clickPoint.y);
if (rectangle == null) {
rectangle = new Rectangle(x, y, w, h);
} else {
rectangle.setBounds(x, y, w, h);
}
}
repaint();
}
}
};
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
Graphics2D graphics2D = (Graphics2D) g.create();
if (rectangle != null) {
Area fill = new Area(new Rectangle(new Point(0, 0), getSize()));
fill.subtract(new Area(rectangle));
if (clickPoint != null) {
graphics2D.setColor(new Color(0, 0, 0, 0));
} else {
graphics2D.setColor(new Color(0, 0, 0, 200));
}
int x = rectangle.x;
int y = rectangle.y;
int w = rectangle.width;
int h = rectangle.height;
graphics2D.fill(fill);
graphics2D.setColor(Color.WHITE);
graphics2D.setStroke(
new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 6 }, 0));
graphics2D.drawRect(x, y, w, h);
if (w >= 30 && h >= 30) {
graphics2D.setStroke(new BasicStroke(3));
graphics2D.drawLine(x + 1, y + 1, x + 8, y + 1);
graphics2D.drawLine(x + 1, y + 1, x + 1, y + 8);
graphics2D.drawLine(x + w - 1, y + 1, x + w - 8, y + 1);
graphics2D.drawLine(x + w - 1, y + 1, x + w - 1, y + 8);
graphics2D.drawLine(x + 1, y + h - 1, x + 8, y + h - 1);
graphics2D.drawLine(x + 1, y + h - 1, x + 1, y + h - 8);
graphics2D.drawLine(x + w - 1, y + h - 1, x + w - 8, y + h - 1);
graphics2D.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 8);
}
}
graphics2D.dispose();
g.dispose();
}
private int getCursorState() {
switch (getCursor().getType()) {
case Cursor.CROSSHAIR_CURSOR:
return HOVERING;
case Cursor.MOVE_CURSOR:
return MOVING;
case Cursor.SW_RESIZE_CURSOR:
case Cursor.SE_RESIZE_CURSOR:
case Cursor.NW_RESIZE_CURSOR:
case Cursor.NE_RESIZE_CURSOR:
case Cursor.N_RESIZE_CURSOR:
case Cursor.S_RESIZE_CURSOR:
case Cursor.W_RESIZE_CURSOR:
case Cursor.E_RESIZE_CURSOR:
return RESIZING;
default:
return -1;
}
}
}
Firstly just to note, the aspect ratio you are using is 3:4 not 4:3:
3:4 means that for every 3 units of width there are 4 units of height.
4:3 means that for every 4 units of width, there are 3 units of height.
w = h / 4 * 3 is calculating 3:4, not 4:3.
w = h / 3 * 4 or h = w / 4 * 3 calculates 4:3
Moving on to why your resizing breaks, when you create a Rectangle you provide the x, y coordinates of it's top left corner, and it's width and height:
Rectangle rectangle = new Rectangle(x, y, width, height)
The rectangle will then be drawn from x, y to x + width, y + height
The resizing part of your code works fine, when the mouse is dragged you update x, y, width, and height correctly.
The reason why applying the aspect ratio breaks it, is because you are updating width, and height, but you are not updating x and y.
Lets say the user performed a Northwest resize, and you now have a rectangle as follows:
x => 10
y => 10
width => 5
height => 10
You then apply your aspect ratio w = h / 4 * 3:
x => 10
y => 10
width => 8
height => 10
Because you are drawing from the top left corner, the rectangle has now grown from left to right, but you want it to grow from right to left. When you resize in the Northwest direction, you always want the bottom right corner of the rectangle to remain in the same place. The reason why this does not happen with your code is because when you apply the aspect ratio to the rectangle's width, you do not then update the start x, y point of the rectangle.
Using the above example, x and y should be updated as follows:
x => 7
y => 10
width => 8
height => 10
Here is a solution that I came up with:
else if (getCursorState() == RESIZING) {
Point startPoint = null;
Point endPoint = null;
switch(getCursor().getType()) {
case Cursor.SW_RESIZE_CURSOR:
startPoint = new Point((int) mouse.getX(), (int) rectangle.getMinY());
endPoint = new Point((int) rectangle.getMaxX(), (int) mouse.getY());
break;
case Cursor.NW_RESIZE_CURSOR:
startPoint = new Point((int) mouse.getX(), (int) mouse.getY());
endPoint = new Point((int) rectangle.getMaxX(), (int) rectangle.getMaxY());
break;
case Cursor.NE_RESIZE_CURSOR:
startPoint = new Point((int) rectangle.getMinX(), (int) mouse.getY());
endPoint = new Point((int) mouse.getX(), (int) rectangle.getMaxY());
break;
case Cursor.SE_RESIZE_CURSOR:
startPoint = new Point((int) rectangle.getMinX(), (int) rectangle.getMinY());
endPoint = new Point((int) mouse.getX(), (int) mouse.getY());
break;
}
rectangle.setFrameFromDiagonal(startPoint, endPoint);
if (fixedRatio) {
// Calculate 3:4 aspect ratio
rectangle.height = rectangle.width / 3 * 4;
// If this is a NW or NE resize, we need to adjust the start y coordinate to account for the new height
// This keeps the bottom right corner in the same place for a NW resize
// and the bottom left corner in the same place for a NE resize
if (getCursor().getType() == Cursor.NW_RESIZE_CURSOR || getCursor().getType() == Cursor.NE_RESIZE_CURSOR) {
rectangle.y = endPoint.y - rectangle.height;
}
}
}
So when the rectangle is resized in the Northwest or Northeast directions, and the aspect ratio is applied, I also update the rectangle's start y coordinate to account for the change in height.

How to draw bitmap image on top in arc

I want to draw image on Top in each Arc of Canvas
private void drawImage(Canvas canvas, float tempAngle, Bitmap bitmap,String mValue) {
//get every arc img width and angle
int imgWidth = (radius / mWheelItems.size());
//int imgWidth = (radius / 3);
float angle = (float) ((tempAngle + 360 / mWheelItems.size() /2) * Math.PI / 180);
//calculate x and y
int x = (int) (center + radius / 2 / 2 * Math.cos(angle));
int y = (int) (center + radius / 2 / 2 * Math.sin(angle));
int top=y - imgWidth/2;
int bottom=y +imgWidth/2;
int left=x - imgWidth /2;
int right=x + imgWidth / 2;
Rect rect = new Rect(left, top, right, bottom);
final Rect rect1 = new Rect(x - imgWidth /2 , y - imgWidth / 2 , bitmap.getWidth() , bitmap.getHeight());
canvas.drawBitmap(bitmap, null, rect, null);
}
the Arc is made according to the size of items
The Result is shown like that
But I want the image bitmap shown on top like that of rect. Red also want to large size of images or bitmap
Solved by Specific Tab and Big Screen Tablets
Change the X and Y coordination According to Angle
if(tempAngle==0) {
x = x + 50;
}
if(tempAngle==60) {
y = y + 50;
}
if(tempAngle==120) {
imgWidth = imgWidth-12;
y = y + 20;
x = x - 40;
}
if(tempAngle==180) {
imgWidth = imgWidth+12;
x = x - 50;
}
if(tempAngle==240) {
y = y - 50;
}
if(tempAngle==300) {
y = y - 20;
x = x + 40;
}

java get center of each shape

hello i'm having trouble drawing arrows from center of a circle to center of the next one, each circle is from a xml elsewhere let's consider size is 14.
why does my code seems not to do the trick?
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import javax.swing.JFrame;
Just setting the frame
public class GRAPHICS_REPRESENTATION extends JFrame {
private Vector<Point> point_tab;
public GRAPHICS_REPRESENTATION() {
super("graphic");
point_tab = new Vector<Point>(0);
setSize(800, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
Drawing a circle (found and reworked from here)
// Convenience method to draw from center with radius
public void drawCircle(Graphics cg, int xCenter, int yCenter, int r) {
Graphics2D cg2 = (Graphics2D) cg.create();
cg2.drawOval(xCenter - r, yCenter - r, r, r);
}// end drawCircle
the problem method
private void disposeScene(Graphics g1, int x1, int y1, int r) {
Graphics2D g = (Graphics2D) g1.create();
AffineTransform at = g.getTransform();
AffineTransform at2 = new AffineTransform();
at2 = AffineTransform.getScaleInstance(0.5, 0.5); // scaling à faire en 1er
g.transform(at2); // prise en compte de la matrice
at2 = AffineTransform.getTranslateInstance(getWidth() / 2 + x1 + r / 2, getHeight() / 2 - y1 - r / 2); // centrage
g.transform(at2);
double angle = (double) Math.cos(0);
for (int i = 0; i < 14; i++) {
angle = Math.rint(angle / (i + 1));
g.setColor(Color.RED);
drawCircle(g, 0, 0, 2 * r);
Point center = new Point();
center.setLocation(g.getTransform().getTranslateX() / 2 + r / 2 + x1 / 2,
g.getTransform().getTranslateY() / 2 - r / 2 - y1 / 2);
point_tab.add(center);
at2.concatenate(AffineTransform.getRotateInstance(angle)); // rotation autour d'un centre
g.transform(at2);
System.out.println(point_tab.elementAt(i).getX() + "," + point_tab.elementAt(i).getY());
g.setColor(Color.BLUE);
if (i + 1 < point_tab.size()) {
drawArrow(g, point_tab.elementAt(i).getX(), point_tab.elementAt(i).getY(),
point_tab.elementAt(i + 1).getX(), point_tab.elementAt(i + 1).getY());
} else {
drawArrow(g, point_tab.elementAt(i).getX(), point_tab.elementAt(i).getY(),
point_tab.elementAt(0).getX(), point_tab.elementAt(0).getY());
}
}
g.setTransform(at);
}
drawing an arrow from src to dst (found here and reworked)
private final int ARR_SIZE = 4;
private void drawArrow(Graphics g1, double xsrc, double ysrc, double xdst, double ydst) {
Graphics2D g = (Graphics2D) g1.create();
double dx = xdst - xsrc, dy = ydst - ysrc; // distances
double angle = Math.atan2(dy, dx);
int len = (int) Math.sqrt(dx * dx + dy * dy);
AffineTransform at = g.getTransform();
AffineTransform at2 = new AffineTransform();
at2=AffineTransform.getTranslateInstance(xsrc, ysrc);
at2.concatenate(AffineTransform.getRotateInstance(angle));
g.transform(at2);
// Draw horizontal arrow starting in (0, 0)
g.drawLine(0, 0, len, 0);
g.fillPolygon(new int[] { len, len - ARR_SIZE, len - ARR_SIZE, len }, new int[] { 0, -ARR_SIZE, ARR_SIZE, 0 },
4);
g.setTransform(at);
}
main method
public void paint(Graphics g) {
disposeScene(g, getWidth()/4,getHeight()/4,40);
}
Here the solution I found by myself
/**
* #brief draw the scene with all shapes set up
* #param g1
* #param x1
* #param y1
* #param xtg
* #param r
*/
private void disposeScene(Graphics g1, int x1, int y1, XML_TO_GRAPH xtg, int r) {
Graphics2D g = (Graphics2D) g1.create();
g.translate(getWidth() / 2, getHeight() / 2);
drawCircle(g, 0, 0, (x1+y1)/2); // cercle fictif
for (int i = 0; i < xtg.getsceneVector().size(); i++) {
double angle = Math.toRadians(360.0); // radian mieux 2pi
angle = (angle*i / xtg.getsceneVector().size());
System.out.println("angle(" + i + ")=" + angle);
g.setColor(Color.RED);
drawCircle(g, (int) (Math.cos(angle) * x1), (int) (Math.sin(angle) * y1), r);
Point center_big_circle = new Point();
center_big_circle.setLocation((0), (0)); // centre du grand cercle fictif
Point center_little_circle = new Point();
center_little_circle.setLocation((Math.cos(angle) * (x1)), (Math.sin(angle) * (y1))); // décalage vers les
// bords
System.out.println("centre(" + i + ")=" + center_little_circle.getX() + "," + center_little_circle.getY());
point_tab.add(center_little_circle);
g.setColor(Color.BLACK);
drawString(g, (int) center_little_circle.getX()-r, (int) center_little_circle.getY()-r, 16, "scène : " + i);
System.out.println(point_tab.elementAt(i).getX() + "," + point_tab.elementAt(i).getY());
g.setColor(Color.BLUE);
if (i + 1 < point_tab.size()) {// si existe
drawArrow(g, point_tab.elementAt(i).getX(), point_tab.elementAt(i).getY(),
point_tab.elementAt(i + 1).getX(), point_tab.elementAt(i + 1).getY());
// g.setColor(Color.BLACK);
// drawString(g, (int)(( point_tab.elementAt(i+1).getX()-
point_tab.elementAt(i).getX())/2), (int) ((point_tab.elementAt(i+1).getY()-
point_tab.elementAt(i).getY())/2), 16, "X : " +
xtg.getcount_occurence().toString());
//idem
drawArrow(g, point_tab.elementAt(i+1).getX(), point_tab.elementAt(i+1).getY(),
point_tab.elementAt(i).getX(), point_tab.elementAt(i).getY());
// drawString(g, (int)(( point_tab.elementAt(i).getX()-
point_tab.elementAt(i+1).getX())/2), (int) ((point_tab.elementAt(i).getY()-
point_tab.elementAt(i+1).getY())/2), 16, "X : " +
xtg.getcount_occurence().toString());
}
}
}
and
// Convenience method to draw from center with radius
/**
*
* #param cg
* #param xCenter
* #param yCenter
* #param r
*/
public void drawCircle(Graphics cg, int xCenter, int yCenter, int r) {
Graphics2D cg2 = (Graphics2D) cg.create();
System.out.println("Center at: " + (xCenter - r) + "," + (yCenter - r));
cg2.drawOval(xCenter - r, yCenter - r, 2 * r, 2 * r);
}// end drawCircle
and convenient drawString method :
/**
*
* #param g1
* #param x
* #param y
* #param size
* #param str
*/
private void drawString(Graphics g1, int x, int y, int size, String str) {
Graphics2D g = (Graphics2D) g1.create();
g.setFont(new Font("Times New Roman", Font.PLAIN, size));
g.drawString(str, x, y);
}
and paint :
public void paint(Graphics g) {
disposeScene(g, (int) (getWidth() / 3), (int) (getHeight() / 3), 20);
}

How to make some of my rectangles Golden (Ratio)?

i'm not too sure on how to make it so when a rectangle is drawn onto the screen, there's a chance that it will be golden. Here's the current code i have for my game to randomly produce random rectangles:
public void drawRectangle() {
rects.clear();
int x = (int) (Math.random() * getWidth());
int y = (int) (Math.random() * getHeight());
int width = (int) (Math.random() * (getWidth() / 4));
int height = (int) (Math.random() * (getHeight() / 4));
if (x + width > getWidth()) {
x = getWidth() - width;
}
if (y + height > getHeight()) {
y = getHeight() - height;
}
Color color = new Color(
(int) (Math.random() * 255),
(int) (Math.random() * 255),
(int) (Math.random() * 255));
rects.add(new Rect(x, y, width, height, color));
repaint();
}
And heres the code i tried using to make it golden, although this was taken from online, i was jsut trying to get it working: EDIT: This code below is effectively now useless, but i'll keep it in the psot in case its of use
public static double golden(int n) {
if (n == 0) return 1;
return 1.0 + 1.0 / golden(n-1);
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
System.out.println(golden(n));
}
Any help is greatly appreciated! Thanks a bunch yet again
The basic idea is, you want to, randomly, create a golden rectangle (and possibly, randomly create the width or height)
You could use Math.random and if it's within a specified range (ie 0.75-1.0), generate a golden rectangle, but I'm lazy, so I'd use Random#nextBoolean to make the decision itself, for example...
private Random random = new Random(System.currentTimeMillis());
public void drawRectangle() {
rects.clear();
double x = (Math.random() * getWidth());
double y = (Math.random() * getHeight());
double width = 0;
double height = 0;
if (random.nextBoolean()) {
if (random.nextBoolean()) {
width = (Math.random() * (getWidth() / 4));
height = width * 1.618;
} else {
height = (Math.random() * (getHeight() / 4));
width = height * 1.618;
}
} else {
width = (Math.random() * (getWidth() / 4));
height = (Math.random() * (getHeight() / 4));
}
if (x + width > getWidth()) {
x = getWidth() - width;
}
if (y + height > getHeight()) {
y = getHeight() - height;
}
Color color = new Color(
(int) (Math.random() * 255),
(int) (Math.random() * 255),
(int) (Math.random() * 255));
rects.add(new Rect(x, y, width, height, color));
repaint();
}
Because the calculation of the golden width/height will generate a double value, I've opted to use doubles, you'll find that Rectangle2D.Double will be useful here and Graphics2D can paint Shape objects (see Graphics2D#draw and Graphics2D#fill)

Using JSlider to Scale Drawing

First question ever here. I'm trying to scale a custom drawing with JSlider. However, it doesn't do anything and I cannot for the life of me figure out why. My code grabs a custom shape and draws it fine initially, but it won't scale.
class DrawFrame extends JFrame {
private int CarWidth = 50;
private CarShape shape = new CarShape(150, 150, CarWidth);
public DrawFrame()
{
setTitle("Draw a Car");
setSize(400, 400);
JSlider slider = new JSlider(JSlider.VERTICAL, 1, 100, 50);
slider.setMajorTickSpacing(5);
slider.setPaintTicks(true);
slider.addChangeListener((new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
int x = (int)source.getValue();
CarWidth = x;
repaint();
}
}));
add(slider, BorderLayout.WEST);
add(shape);
}
}
public class CarShape extends JPanel {
private int x;
private int y;
private int width;
public CarShape(int x, int y, int width)
{
this.x = x;
this.y = y;
this.width = width;
}
public void update(int x){
x = width;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D.Double body
= new Rectangle2D.Double(x, y + width / 6,
width - 1, width / 6);
Ellipse2D.Double frontTire
= new Ellipse2D.Double(x + width / 6, y + width / 3,
width / 6, width / 6);
Ellipse2D.Double rearTire
= new Ellipse2D.Double(x + width * 2 / 3, y + width / 3,
width / 6, width / 6);
// The bottom of the front windshield
Point2D.Double r1
= new Point2D.Double(x + width / 6, y + width / 6);
// The front of the roof
Point2D.Double r2
= new Point2D.Double(x + width / 3, y);
// The rear of the roof
Point2D.Double r3
= new Point2D.Double(x + width * 2 / 3, y);
// The bottom of the rear windshield
Point2D.Double r4
= new Point2D.Double(x + width * 5 / 6, y + width / 6);
Line2D.Double frontWindshield
= new Line2D.Double(r1, r2);
Line2D.Double roofTop
= new Line2D.Double(r2, r3);
Line2D.Double rearWindshield
= new Line2D.Double(r3, r4);
g2.draw(body);
g2.draw(frontTire);
g2.draw(rearTire);
g2.draw(frontWindshield);
g2.draw(roofTop);
g2.draw(rearWindshield);
}
}
public class SliderTester {
public static void main(String[] args)
{
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Every time the change listener is called, it creates a new CarShape object, but this has no effect on the CarShape object that is displayed. Better perhaps would be to resize the visualized object... OK, did you just change the code on me or am I imagining things?
Now you're changing CarWidth (which should be re-named carWidth), but that's not going to change the state of the visualized CarShape object. Instead give your CarShape class a setCarWidth(int width) method, one that changes its state, and then call that method within your stateChange method.
e.g.,
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
#SuppressWarnings("serial")
class DrawFrame extends JFrame {
private int carWidth = 50;
private CarShape shape = new CarShape(150, 150, carWidth);
public DrawFrame() {
setTitle("Draw a Car");
setSize(400, 400);
JSlider slider = new JSlider(JSlider.VERTICAL, 1, 100, 50);
slider.setMajorTickSpacing(5);
slider.setPaintTicks(true);
slider.addChangeListener((new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
carWidth = (int) source.getValue();
shape.setCarWidth(carWidth);
repaint();
}
}));
add(slider, BorderLayout.WEST);
add(shape);
}
}
#SuppressWarnings("serial")
class CarShape extends JPanel {
private int x;
private int y;
private int width;
public CarShape(int x, int y, int width) {
this.x = x;
this.y = y;
this.width = width;
}
public void setCarWidth(int w) {
this.width = w;
}
// this method is just messed up -- you're setting the parameter!
public void update(int x) {
x = width; // no!!!
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D.Double body = new Rectangle2D.Double(x, y + width / 6,
width - 1, width / 6);
Ellipse2D.Double frontTire = new Ellipse2D.Double(x + width / 6, y
+ width / 3, width / 6, width / 6);
Ellipse2D.Double rearTire = new Ellipse2D.Double(x + width * 2 / 3, y
+ width / 3, width / 6, width / 6);
// The bottom of the front windshield
Point2D.Double r1 = new Point2D.Double(x + width / 6, y + width / 6);
// The front of the roof
Point2D.Double r2 = new Point2D.Double(x + width / 3, y);
// The rear of the roof
Point2D.Double r3 = new Point2D.Double(x + width * 2 / 3, y);
// The bottom of the rear windshield
Point2D.Double r4 = new Point2D.Double(x + width * 5 / 6, y + width / 6);
Line2D.Double frontWindshield = new Line2D.Double(r1, r2);
Line2D.Double roofTop = new Line2D.Double(r2, r3);
Line2D.Double rearWindshield = new Line2D.Double(r3, r4);
g2.draw(body);
g2.draw(frontTire);
g2.draw(rearTire);
g2.draw(frontWindshield);
g2.draw(roofTop);
g2.draw(rearWindshield);
}
}
public class SliderTester {
public static void main(String[] args) {
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Categories