Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
Maths101 question - does anyone know how to calculate an ellipse (width/height) that will enclose a given rectangle. Obviously there is no single ellipse - I'm after an algorithm that will give me various width/height combinations - or perhaps the smallest area of ellipse? It's for a GUI, so an aesthetically pleasing ratio of height/width is what I'm looking for.
Thanks in advance.
If you give your ellipse the same aspect ratio as the rectangle, you can work on the basis that what you want is a circle enclosing a square then stretched as if you've transformed the square into the required rectangle.
For a square with half side length = 1, the radius of the circle would be sqrt(2).
So, sweeping theta from 0 - 360', the ellipse's coordinate points will be:
x = cos(theta) * sqrt(2) * rect.width + x.center;
y = sin(theta) * sqrt(2) * rect.height + y.center;
where rect.width and rect.height are the half widths of the relevant sides.
Ellipse formula is (x/A)^2+(y/B)^2=1, where A and B are radiuses of ellipse
Rectangle sides are Rw and Rh
Let's assume we want ellipse with same proportions as rectangle; then, if we image square in circle (A=B,Rq=Rh) and squeeze it, we well keep ratio of ellipse A/B same as ratio of rectangle sides Rw/Rh;
This leads us to following system of equations:
(x/A)^2+(y/B)^2=1
A/B=Rw/Rh
Lets solve it:
A=B*(Rw/Rh)
(Rh/2B)^2+(Rh/2B)^2=1
Rh=sqrt(2)*B
And final solution:
A=Rw/sqrt(2)
B=Rh/sqrt(2)
Example:
The equation for a ellipse centered in the origin is
(x/A)^2 + (y/B)^2 = 1
Now if you want to enclose a rectangle of MxN with a eclipse you can move its center to the origin of coordinates. The top right coordinates are (M/2,N/2), replacing in the ellipse equation you have a formula you can use to solve B given A (or A given B).
If you have a rectangle of 4x2, the top-right coordinates are (2,1), replacing you have the (2/A)^2 + (1/B)^2 = 1, then if A=4 solving for B gives B=1/sqrt(1-(1/2)^2).
Experimentally, I found that an ellipse defined by a rectangle that is sqrt(2) larger than the inner rectangle works. So pass sqrt(2) to this function, and you will get the appropriate rectangle:
RectangleF boundingEllipse = GetScaledRectangle(innerRect, Convert.ToSingle(Math.Sqrt(2d)));
private RectangleF GetScaledRectangle(RectangleF rect, float scale)
{
float width = rect.Width * scale;
float height = rect.Height * scale;
float gap = width - rect.Width;
float left = rect.Left - (gap / 2f);
gap = height - rect.Height;
float top = rect.Top - (gap / 2f);
return new RectangleF(left, top, width, height);
}
Assuming you mean circumscribed (which is more precise than "enclosed"), you can read about how to circumscribe a rectangle here. From there, you can stretch it to rectangular, as Alnitak says.
Related
So to give further context lets say I have an image that is 200px by 200px with a rectangle on it, its red below:
I know the height and width of the image, the coordinates of the rectangle and also the height and width of the red rectangle.
So what I need to know is if I flip this whole image (including the rectangle) is there a way to work out what the new coordinates are of the red rectangle? I'd imagine there must be some kind of formula or algorithm I can apply to get these new coordinates.
This was already answered over here. The below is the function that worked best for my use case which is very similar to yours.
def rotate(point, origin, degrees):
radians = np.deg2rad(degrees)
x,y = point
offset_x, offset_y = origin
adjusted_x = (x - offset_x)
adjusted_y = (y - offset_y)
cos_rad = np.cos(radians)
sin_rad = np.sin(radians)
qx = offset_x + cos_rad * adjusted_x + sin_rad * adjusted_y
qy = offset_y + -sin_rad * adjusted_x + cos_rad * adjusted_y
return int(qx), int(qy)
In addition to this sometimes when you rotate the points you get negative values(depending on degrees of rotation), in cases like these you need to add the height and or width of the image you are rotating to the value. In my case below the images were of fixed size (416x416)
def cord_checker(pt1):
for item in pt1:
if item<0:
pt1[pt1.index(item)]=416+item
else: pass
return pt1
finally to get the coordinates of the rotated point
pt1=tuple(cord_checker(list(rotate((xmi,ymi),origin=(0,0),degrees*=))))
*degrees can be 90,180 etc
If the image is centered around the origin (0,0), you can just flip the signs of the x-coordinates to do a horizontal flip or the y-coordinates to do a vertical flip while preserving the origin as your center.
You can also flip an arbitrary image by flipping the signs:
# Horizontal flip
new_x = -x
new_y = y
# Vertical flip
new_x = x
new_y = -y
but the center coordinates will not be the same. If you want the same center coordinates, you'd have to shift it back.
I have two rectangles: red and green. For each of them, I have the following information:
Center point (x and y coords).
Rotation angle
Width and height
The rectangles will always be moving in positive coordinates. Edit: No coordinate can ever be negative: the rectangles are always located in positive coordinates. Therefore, the center will never be (0,0).
Problem
I have an starting position. To simplify the example, let's say that my red and green rectangles are located as follows:
Now, I rotate the red rectangle using an angle phi which goes between 0º and 90º. However, the green rectangles needs to rotate and keep its position regarding the red rectangle. The green rectangle is not only rotating but also moving.
Let see an image (please excuse the sketch-quality):
My Question:
How can I obtain the new center coords for the green rectangle?
Rotation is about some point (rx, ry).
Edit: As comment says, rotation center (rx, ry) is red center. Formula remains the same.
If green center was at (gx, gy), then after rotation it has coordinates
gx' = rx + (gx - rx) * Cos(Phi) - (gy - ry) * Sin(Phi)
gy' = ry + (gx - rx) * Sin(Phi) + (gy - ry) * Cos(Phi)
How can one calculate the camera distance from an object in 3D space (an image in this case) such that the image is at its original pixel width.
Am I right in assuming that this is possible given the aspect ratio of the camera, fov, and the original width/height of the image in pixels?
(In case it is relevant, I am using THREE.js in this particular instance).
Thanks to anyone who can help or lead me in the right direction!
Thanks everyone for all the input!
After doing some digging and then working out how this all fits into the exact problem I was trying to solve with THREE.js, this was the answer I came up with in JavaScript as the target Z distance for displaying things at their original scale:
var vFOV = this.camera.fov * (Math.PI / 180), // convert VERTICAL fov to radians
var targetZ = window.innerHeight / (2 * Math.tan(vFOV / 2) );
I was trying to figure out which one to mark as the answer but I kind of combined all of them into this solution.
Trigonometrically:
A line segment of length l at a right angle to the view plane and at a distance of n perpendicular to it will subtend arctan(l/n) degrees on the camera. You can arrive at that result by simple trigonometry.
Hence if your field of view in direction of the line is q, amounting to p pixels, you'll end up occupying p*arctan(l/n)/q pixels.
So, using y as the output number of pixels:
y = p*arctan(l/n)/q
y*q/p = arctan(l/n)
l/tan(y*q/p) = n
Linear algebra:
In a camera with a field-of-view of 90 degrees and a viewport of 2w pixels wide, the projection into screen space is equivalent to:
x' = w - w*x/z
When perpendicular, the length of a line on screen is the difference between two such xs so by normal associativity and commutivity rules:
l' = w - w*l/z
Hence:
w - l' = w*l/z
z = (w - l') / (w*l)
If your field of view is actually q degrees rather than 90 then you can use the cotangent to scale appropriately.
In your original question you said that you're using css3D. I suggest that you do the following:
Set up an orthographic camera with fov = 1..179 degrees, where left = screenWidth / 2, right = screenWidth / - 2, top = screenHeight / 2, bottom = screenHeight / - 2. Near and far planes do not affect CSS3D rendering as far as I can tell from experience.
camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far);
camera.fov = 75;
now you need to calculate the distance between the camera and object in such way that when the object is projected using the camera with settings above, the object has 1:1 coordinate correspondence on screen. This can be done in following way:
var camscale = Math.tan(( camera.fov / 2 ) / 180 * Math.PI);
var camfix = screenHeight / 2 / camscale;
place your div to position: x, y, z
set the camera's position to 0, 0, z + camfix
This should give you 1:1 coordinate correspondence with rendered result and your pixel values in css / div styles. Remember that the origin is in center and the object's position is the center of the object so you need to do adjustments in order to achieve coordinate specs from top-left corner for example
object.x = ( screenWidth - objectWidth ) / 2 + positionLeft
object.y = ( screenHeight - objectHeight ) / 2 + positionTop
object.z = 0
I hope this helps, I was struggling with same thing (exact control of the css3d scene) but managed to figure out that the Orthographic camera + viewport size adjusted distance from object did the trick. Don't alter the camera rotation or its x and y coordinates, just fiddle with the z and you're safe.
I understand how to calculate the largest possible rectangle that can be drawn inside an ellipse, but my problem is: I a have a rectangle of given proportions and an ellipse of a given size (not the same proportions) and I need to know how big that rectangle will be when centered inside the ellipse and sized with all four corners intersecting.
If the rectangle is centered inside the ellipse, and for all 4 corners to lie on the ellipse, the 4 corners must be the solution to the equation system of:
[1] implicit equation of the ellipse: x^2/a^2 + y^2/b^2 = 1
[2] The proportion of the rectangle (aspect ratio) x / y = c.
Just substitute in and solve the equation for x and y. 2 * abs(x) will be the width and 2 * abs(y) will be the height of the rectangle.
I'm writing a script where icons rotate around a given pivot (or origin). I've been able to make this work for rotating the icons around an ellipse but I also want to have them move around the perimeter of a rectangle of a certain width, height and origin.
I'm doing it this way because my current code stores all the coords in an array with each angle integer as the key, and reusing this code would be much easier to work with.
If someone could give me an example of a 100x150 rectangle, that would be great.
EDIT: to clarify, by rotating around I mean moving around the perimeter (or orbiting) of a shape.
You know the size of the rectangle and you need to split up the whole angle interval into four different, so you know if a ray from the center of the rectangle intersects right, top, left or bottom of the rectangle.
If the angle is: -atan(d/w) < alfa < atan(d/w) the ray intersects the right side of the rectangle. Then since you know that the x-displacement from the center of the rectangle to the right side is d/2, the displacement dy divided by d/2 is tan(alfa), so
dy = d/2 * tan(alfa)
You would handle this similarily with the other three angle intervals.
Ok, here goes. You have a rect with width w and depth d. In the middle you have the center point, cp. I assume you want to calculate P, for different values of the angle alfa.
I divided the rectangle in four different areas, or angle intervals (1 to 4). The interval I mentioned above is the first one to the right. I hope this makes sense to you.
First you need to calculate the angle intervals, these are determined completely by w and d. Depending on what value alfa has, calculate P accordingly, i.e. if the "ray" from CP to P intersects the upper, lower, right or left sides of the rectangle.
Cheers
This was made for and verified to work on the Pebble smartwatch, but modified to be pseudocode:
struct GPoint {
int x;
int y;
}
// Return point on rectangle edge. Rectangle is centered on (0,0) and has a width of w and height of h
GPoint getPointOnRect(int angle, int w, int h) {
var sine = sin(angle), cosine = cos(angle); // Calculate once and store, to make quicker and cleaner
var dy = sin>0 ? h/2 : h/-2; // Distance to top or bottom edge (from center)
var dx = cos>0 ? w/2 : w/-2; // Distance to left or right edge (from center)
if(abs(dx*sine) < abs(dy*cosine)) { // if (distance to vertical line) < (distance to horizontal line)
dy = (dx * sine) / cosine; // calculate distance to vertical line
} else { // else: (distance to top or bottom edge) < (distance to left or right edge)
dx = (dy * cosine) / sine; // move to top or bottom line
}
return GPoint(dx, dy); // Return point on rectangle edge
}
Use:
rectangle_width = 100;
rectangle_height = 150;
rectangle_center_x = 300;
rectangle_center_y = 300;
draw_rect(rectangle_center_x - (rectangle_width/2), rectangle_center_y - (rectangle_center_h/2), rectangle_width, rectangle_height);
GPoint point = getPointOnRect(angle, rectangle_width, rectangle_height);
point.x += rectangle_center_x;
point.y += rectangle_center_y;
draw_line(rectangle_center_x, rectangle_center_y, point.x, point.y);
One simple way to do this using an angle as a parameter is to simply clip the X and Y values using the bounds of the rectangle. In other words, calculate position as though the icon will rotate around a circular or elliptical path, then apply this:
(Assuming axis-aligned rectangle centered at (0,0), with X-axis length of XAxis and Y-axis length of YAxis):
if (X > XAxis/2)
X = XAxis/2;
if (X < 0 - XAxis/2)
X = 0 - XAxis/2;
if (Y > YAxis/2)
Y = YAxis/2;
if (Y < 0 - YAxis/2)
Y = 0 - YAxis/2;
The problem with this approach is that the angle will not be entirely accurate and the speed along the perimeter of the rectangle will not be constant. Modelling an ellipse that osculates the rectangle at its corners can minimize the effect, but if you are looking for a smooth, constant-speed "orbit," this method will not be adequate.
If think you mean rotate like the earth rotates around the sun (not the self-rotation... so your question is about how to slide along the edges of a rectangle?)
If so, you can give this a try:
# pseudo coode
for i = 0 to 499
if i < 100: x++
else if i < 250: y--
else if i < 350: x--
else y++
drawTheIcon(x, y)
Update: (please see comment below)
to use an angle, one line will be
y / x = tan(th) # th is the angle
the other lines are simple since they are just horizontal or vertical. so for example, it is x = 50 and you can put that into the line above to get the y. do that for the intersection of the horizontal line and vertical line (for example, angle is 60 degree and it shoot "NorthEast"... now you have two points. Then the point that is closest to the origin is the one that hits the rectangle first).
Use a 2D transformation matrix. Many languages (e.g. Java) support this natively (look up AffineTransformation); otherwise, write out a routine to do rotation yourself, once, debug it well, and use it forever. I must have five of them written in different languages.
Once you can do the rotation simply, find the location on the rectangle by doing line-line intersection. Find the center of the orbited icon by intersecting two lines:
A ray from your center of rotation at the angle you desire
One of the four sides, bounded by what angle you want (the four quadrants).
Draw yourself a sketch on a piece of paper with a rectangle and a centre of rotation. First translate the rectangle to centre at the origin of your coordinate system (remember the translation parameters, you'll need to reverse the translation later). Rotate the rectangle so that its sides are parallel to the coordinate axes (same reason).
Now you have a triangle with known angle at the origin, the opposite side is of known length (half of the length of one side of the rectangle), and you can now:
-- solve the triangle
-- undo the rotation
-- undo the translation