suppose I have 2 rectangles as follows:
one encloses the other
they share at least 2 sides (3 or all 4 also possible)
how do I get the vector that describes the displacement required for the inner rectangle to move upto the non-shared side(s)?
If i understood you correctly, then you you should follow those steps:
Find corner that both sides are shared.
Get oposit corner from inner and outer rectangles.
vector = outerRecCorner - innerRecCorner
It's more like a math than programming question :)
Lets assume you have two rectangles: A (inside) and B (outside). They have 4 corners:
Point [] GetCorners (Rectangle rect)
{
Point [] corners = new Point[4];
Point corners[0] = new Point(rect.X, rect.Y);
Point corners[1] = new Point(rect.X + rect.Width, rect.Y);
Point corners[2] = new Point(rect.X, rect.Y + rect.Height);
Point corners[3] = new Point(rect.X + rect.Width + rect.Width, rect.Y);
return corners;
}
First find the first shared corner:
Point [] cornersListA = GetCorners(A);
Point [] cornersListB = GetCorners(B);
int sharedCornerIndex = 0;
for (int i=0; i<4; i++)
{
if(cornersListA[i].X==cornersListB[i].X && cornersListA[i].Y==cornersListB[i].Y)
{
sharedCornerIndex = i;
break;
}
}
Then find the corner oposite of it:
int oppositeCornerIndex = 0;
if(sharedCornerIndex ==0) oppositeCornerIndex = 3;
if(sharedCornerIndex ==3) oppositeCornerIndex = 0;
if(sharedCornerIndex ==1) oppositeCornerIndex = 2;
if(sharedCornerIndex ==2) oppositeCornerIndex = 1;
Finally, get vector (I didn't check this part of the code, but it should work):
Vector v = new Vector();
v.X = cornersListB[oppositeCornerIndex].X - cornersListA[oppositeCornerIndex].X;
v.Y = cornersListB[oppositeCornerIndex].Y - cornersListA[oppositeCornerIndex].Y;
Related
I want to increase the height of the curve but its left and right position should remain same. Just want to lift up from center to give it a shape like curve as height changes.
Pen blackPen = new Pen(Color.Black, 3);
// Create coordinates of rectangle to bound ellipse.
int x = 93;
int y = 136;
int width = 320;
int height = 50;
// Create start and sweep angles on ellipse.
int startAngle = 0;
int sweepAngle = -180;
// Draw arc to screen.
e.Graphics.DrawArc(blackPen, x, y, width, height, startAngle, sweepAngle);
In the most direct way your problem can be solved like this:
int change = 0;
e.Graphics.DrawArc(blackPen, x, y-change, width, height+change, startAngle, sweepAngle);
By increasing the variable change the ellipse will curve up more and more:
private void button1_Click(object sender, EventArgs e)
{
change += 10;
panel1.Invalidate();
}
But maybe you want more control over the shape? Let's have a look at the options:
Here are examples of the three 'curve' drawing methods:
Curves, Beziers & Ellipses
And here is the code to draw that image.
Please ignore the Graphics.xxxTransform calls! They only are meant to shift the curves a little bit upwards so they don't overlap too much to see them properly.
Also note that the curves in the first image are not completely convex. See the last part of the answer to see a DrawCurve call that avoids the concave segments!
The important part are the Points! And just as the comments suggest, in the third part the ellipses are being changed by making the height larger and moving the top of the Rectangle up by the same amount.
The complexity DrawArc of and DrawCurve is pretty much equal; both are controlled by four integers with a rather clear meaning: They either make one rectangle or the corners of a symmetrical triangle. (Plus one counterpoint for the convex call.)
DrawBezier is more complex, especially since the controls point(s) are not actually on the resulting curve. They can be thought of force vectors that pull the line into a curved shape and are harder to calculate.
private void panel1_Paint(object sender, PaintEventArgs e)
{
Point a = new Point(0, 200);
Point c = new Point(200, 200);
for (int i = 0; i< 10; i++)
{
e.Graphics.TranslateTransform(0, -5);
Point b = new Point(100, 50 + i * 10);
e.Graphics.DrawCurve(Pens.Maroon, new[] { a, b, c }, 0.7f);
}
e.Graphics.ResetTransform();
Point pa = new Point(250, 200);
Point pb = new Point(450, 200);
for (int i = 0; i < 10; i++)
{
e.Graphics.TranslateTransform(0, -5);
Point pc = new Point(350, 200 - i * 10);
e.Graphics.DrawBezier(Pens.ForestGreen, pa, pc, pc, pb);
}
e.Graphics.ResetTransform();
int x = 500;
int y0 = 200;
int w = 200;
for (int i = 0; i < 10; i++)
{
e.Graphics.TranslateTransform(0, -5);
Rectangle rect = new Rectangle(x, y0 - i * 10, w, 10 + i * 10);
e.Graphics.DrawArc(Pens.DarkBlue, rect, -0, -180);
}
e.Graphics.ResetTransform();
}
Notes:
The Curve (1st image) can be further controlled by the Tension parameter. The lower the tension the more pointed it gets, approaching 1f it makes the curve broader..
The Bezier curve (2nd image) is using only one control point. (Twice.) The curve gets a little pointed this way. You can make it broader and broader by using two different points the move apart little by little..
The Ellipse can't be controlled; it will always fill the bounding Rectangle.
Here is an example of varying the Curves and the Beziers:
The Curves are drawn with varying Tensions. Also I have used an overload that helps to get rid of the concave part at the start and end of the curve. The trick is to add a suitable extra point to the start and end and to tell the DrawCurve to leave out these 1st and last segments.
The simplest point to use (for both ends actually) is the counterpoint of the one at the top.
The Beziers are drawn using two control points, moving out and up a little.
Here is the code for the variations:
Point a = new Point(0, 200);
Point c = new Point(200, 200);
for (int i = 1; i < 10; i++)
{
e.Graphics.TranslateTransform(0, -5);
Point b = new Point(100, 50);
Point b0 = new Point(b.X, a.Y + (a.Y - b.Y));
e.Graphics.DrawCurve(Pens.Maroon, new[] { b0, a, b, c, b0 }, 1, 2, 0.1f * i);
}
e.Graphics.ResetTransform();
Point pa = new Point(250, 200);
Point pb = new Point(450, 200);
for (int i = 0; i < 10; i++)
{
e.Graphics.TranslateTransform(0, -5);
Point ca = new Point(350 - i * 9, 100 - i * 5);
Point cb = new Point(350 + i * 9, 100 - i * 5);
e.Graphics.DrawBezier(Pens.ForestGreen, pa, ca, cb, pb);
}
e.Graphics.ResetTransform();
here was the solution just increase value of y0 as u increase the value of
y0-i here i=20
int x = 96;
int y0 = 260;
int w = 320;
e.Graphics.TranslateTransform(0, -5);
Rectangle rect = new Rectangle(x, y0 - 20 * 10, w, 10 + 20 * 10);
e.Graphics.DrawArc(Pens.DarkBlue, rect, -0, -180);
e.Graphics.ResetTransform();
I am using the following to create a circle using VertexPositionTexture:
public static ObjectData Circle(Vector2 origin, float radius, int slices)
{
/// See below
}
The texture that is applied to it doesn't look right, it spirals out from the center. I have tried some other things but nothing does it how I want. I would like for it to kind-of just fan around the circle, or start in the top-left end finish in the bottom-right. Basically wanting it to be easier to create textures for it.
I know that are MUCH easier ways to do this without using meshes, but that is not what I am trying to accomplish right now.
This is the code that ended up working thanks to Pinckerman:
public static ObjectData Circle(Vector2 origin, float radius, int slices)
{
VertexPositionTexture[] vertices = new VertexPositionTexture[slices + 2];
int[] indices = new int[slices * 3];
float x = origin.X;
float y = origin.Y;
float deltaRad = MathHelper.ToRadians(360) / slices;
float delta = 0;
float thetaInc = (((float)Math.PI * 2) / vertices.Length);
vertices[0] = new VertexPositionTexture(new Vector3(x, y, 0), new Vector2(.5f, .5f));
float sliceSize = 1f / slices;
for (int i = 1; i < slices + 2; i++)
{
float newX = (float)Math.Cos(delta) * radius + x;
float newY = (float)Math.Sin(delta) * radius + y;
float textX = 0.5f + ((radius * (float)Math.Cos(delta)) / (radius * 2));
float textY = 0.5f + ((radius * (float)Math.Sin(delta)) /(radius * 2));
vertices[i] = new VertexPositionTexture(new Vector3(newX, newY, 0), new Vector2(textX, textY));
delta += deltaRad;
}
indices[0] = 0;
indices[1] = 1;
for (int i = 0; i < slices; i++)
{
indices[3 * i] = 0;
indices[(3 * i) + 1] = i + 1;
indices[(3 * i) + 2] = i + 2;
}
ObjectData thisData = new ObjectData()
{
Vertices = vertices,
Indices = indices
};
return thisData;
}
public static ObjectData Ellipse()
{
ObjectData thisData = new ObjectData()
{
};
return thisData;
}
ObjectData is just a structure that contains an array of vertices & an array of indices.
Hope this helps others that may be trying to accomplish something similar.
It looks like a spiral because you've set the upper-left point for the texture Vector2(0,0) in the center of your "circle" and it's wrong. You need to set it on the top-left vertex of the top-left slice of you circle, because 0,0 of your UV map is the upper left corner of your texture.
I think you need to set (0.5, 0) for the upper vertex, (1, 0.5) for the right, (0.5, 1) for the lower and (0, 0.5) for the left, or something like this, and for the others use some trigonometry.
The center of your circle has to be Vector2(0.5, 0.5).
Regarding the trigonometry, I think you should do something like this.
The center of your circle has UV value of Vector2(0.5, 0.5), and for the others (supposing the second point of the sequence is just right to the center, having UV value of Vector2(1, 0.5)) try something like this:
vertices[i] = new VertexPositionTexture(new Vector3(newX, newY, 0), new Vector2(0.5f + radius * (float)Math.Cos(delta), 0.5f - radius * (float)Math.Sin(delta)));
I've just edited your third line in the for-loop. This should give you the UV coordinates you need for each point. I hope so.
How can i draw a polygon according to the input coordinates which are given in C#.
You didn't show any code because based on those coordinate, you are applying some form of scaling to the image.
Using the Paint event of a PictureBox, here is an example using those coordinates on the screen. It fills in the polygon, then draws the border, then it loops through all the points to draw the red circle:
void pictureBox1_Paint(object sender, PaintEventArgs e) {
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.Clear(Color.White);
// draw the shading background:
List<Point> shadePoints = new List<Point>();
shadePoints.Add(new Point(0, pictureBox1.ClientSize.Height));
shadePoints.Add(new Point(pictureBox1.ClientSize.Width, 0));
shadePoints.Add(new Point(pictureBox1.ClientSize.Width,
pictureBox1.ClientSize.Height));
e.Graphics.FillPolygon(Brushes.LightGray, shadePoints.ToArray());
// scale the drawing larger:
using (Matrix m = new Matrix()) {
m.Scale(4, 4);
e.Graphics.Transform = m;
List<Point> polyPoints = new List<Point>();
polyPoints.Add(new Point(10, 10));
polyPoints.Add(new Point(12, 35));
polyPoints.Add(new Point(22, 35));
polyPoints.Add(new Point(24, 22));
// use a semi-transparent background brush:
using (SolidBrush br = new SolidBrush(Color.FromArgb(100, Color.Yellow))) {
e.Graphics.FillPolygon(br, polyPoints.ToArray());
}
e.Graphics.DrawPolygon(Pens.DarkBlue, polyPoints.ToArray());
foreach (Point p in polyPoints) {
e.Graphics.FillEllipse(Brushes.Red,
new Rectangle(p.X - 2, p.Y - 2, 4, 4));
}
}
}
You may use Graphics.DrawPolygon. You can store the coordinates in an array of Point and then you can pass that to DrawPolygon method. You may wanna see:
Drawing with Graphics in WinForms using C#
private System.Drawing.Graphics g;
System.Drawing.Point[] p = new System.Drawing.Point[6];
p[0].X = 0;
p[0].Y = 0;
p[1].X = 53;
p[1].Y = 111;
p[2].X = 114;
p[2].Y = 86;
p[3].X = 34;
p[3].Y = 34;
p[4].X = 165;
p[4].Y = 7;
g = PictureBox1.CreateGraphics();
g.DrawPolygon(pen1, p);
This simple function is able to generate an array of PointF equal to the vertices of the regular polygon to be drawn, where "center" is the center of the polygon, "sides" is its number of sides, "sideLength" is the size of each side in pixels and "offset" is its slope.
public PointF[] GetRegularPolygonScreenVertex(Point center, int sides, int sideLength, float offset)
{
var points = new PointF[sides];
for (int i = 0; i < sides; i++)
{
points[i] = new PointF(
(float)(center.X + sideLength * Math.Cos((i * 360 / sides + offset) * Math.PI / 180f)),
(float)(center.Y + sideLength * Math.Sin((i * 360 / sides + offset) * Math.PI / 180f))
);
}
return points;
}
The result obtained can be used to draw a polygon, e.g. with the function:
GraphicsObject.DrawPolygon(new Pen(Brushes.Black, GetRegularPolygonScreenVertex(new Point(X, Y), 6, 30, 60f));
Which will generate a regular hexagon with a side of 30 pixels inclined by 30°.
hex
I want to draw the following red polygon:
The problem is if I use somethign like this:
Polygon poly = new Polygon();
poly.StrokeThickness = 2;
poly.Stroke = Brushes.Black;
PointCollection points = new PointCollection();
for (int i = 0; i < this.NumberOfMetrics; i++)
{
points.Add(new Point(MAX_VALUE - this.Metrics[n, i] * Math.Cos(DegreeToRadian(i * (360 / (this.NumberOfMetrics)))), MAX_Y_GUI - this.Metrics[n, i] * Math.Sin(DegreeToRadian(i * (360 / (this.NumberOfMetrics))))));
}
poly.Points = points;
Then the polygon is always "filled" and in the example above the red and green polygon is drawn.
I already tried to add the 4 "inner" points to the PointCollection, but then nothing is drawn. So how can I achieve that?
I tried the solution proposed by David:
for (int n = 0; n < this.NumberOfRevisions; n++)
{
Path path = new Path();
CombinedGeometry geometry = new CombinedGeometry();
geometry.GeometryCombineMode = GeometryCombineMode.Union;
Polygon poly = new Polygon();
PointCollection points = new PointCollection();
for (int i = 0; i < this.NumberOfMetrics; i++)
{
points.Add(new Point(MAX_VALUE - this.Metrics[n, i] * Math.Cos(DegreeToRadian(i * (360 / (this.NumberOfMetrics)))), MAX_Y_GUI - this.Metrics[n, i] * Math.Sin(DegreeToRadian(i * (360 / (this.NumberOfMetrics))))));
}
poly.Points = points;
geometry.Geometry1 = poly.RenderedGeometry;
geometry.Geometry2 = poly.RenderedGeometry;
path.Data = geometry;
polygons.Add(poly);
paths.Add(path);
}
This is just a test but I thougth so I should get the same result as before, but it isn't drawn anything. Is there something wrong with my code?
If you want to have 2 independent shapes, with the possibility of the green one to be transparent as you stated in your comment, the best way to do is to use a combined geometry:
http://msdn.microsoft.com/en-en/library/ms653071%28v=VS.85%29.aspx
with the help of this, you can first create the green geometry, then the red by subtracting the green (or a copy of it) from the red one to create the hole.
So basically:
red shape, PLAIN
green shape on top of it, PLAIN
Subtract green shape or copy of it from red shape >> hole in red shape
this way you get the effect you want
easier done in Xaml, a bit more complicated in C# but still doable.
Edit: set the Combined Geometry as a Path's Data:
Path myPath = new Path();
CombinedGeometry myCombinedGeometry = new CombinedGeometry()
// here you set the combinedGeometry's geometries to create the shape you want
myPath.Data = myCombinedGeometry;
myGrid.Children.Add(myPath);
by the way, the PATH will be the place where you set the Fill / Stroke attribute for the colors, not the inside geometries. (see the examples in xaml in the link above, you basically just have to translate the code into C#)
Edit2:
don't forget to set a Fill on the Path:
for (int n = 0; n < this.NumberOfRevisions; n++)
{
CombinedGeometry geometry = new CombinedGeometry() { GeometryCombineMode = GeometryCombineMode.Union };
PointCollection points = new PointCollection();
for (int i = 0; i < this.NumberOfMetrics; i++)
{
points.Add(new Point(MAX_VALUE - this.Metrics[n, i] * Math.Cos(DegreeToRadian(i * (360 / (this.NumberOfMetrics)))), MAX_Y_GUI - this.Metrics[n, i] * Math.Sin(DegreeToRadian(i * (360 / (this.NumberOfMetrics))))));
}
Polygon poly = new Polygon();
poly.Points = points;
geometry.Geometry1 = poly.RenderedGeometry;
geometry.Geometry2 = poly.RenderedGeometry;
polygons.Add(poly);
paths.Add(path = new Path() { Data = geometry, Fill = Brushes.Red, Stroke = Brushes.Transparent });
}
I posted a previous question about generating a bezier curve based on only the start and end points, and I was able thanks to the answers in that create a bezier curve using the information I have.
This is the code that allows me to draw the types of curve that I want on a form.
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Random rnd = new Random();
Point startp = new Point(rnd.Next(0, this.Width), rnd.Next(0, this.Height));
Point endp = new Point(rnd.Next(0, this.Width), rnd.Next(0, this.Height));
int xMod = 0;
int yMod = 0;
if (startp.X > endp.X) {
xMod = -1;
} else {
xMod = 1;
}
if (startp.Y > endp.Y) {
yMod = 1;
} else {
yMod = -1;
}
Point control1p = new Point(endp.X + (rnd.Next(20, 50) * xMod), endp.Y + (rnd.Next(20, 50) * yMod));
Point control2p = new Point(endp.X + (rnd.Next(5, 20) * xMod), endp.Y + (rnd.Next(5, 20) * yMod));
Point[] pts = {
startp,
control1p,
control2p,
endp
};
Pen dashed_pen = new Pen(Color.Black, 0);
dashed_pen.DashStyle = Drawing2D.DashStyle.Dash;
for (int i = 0; i <= 2; i++) {
e.Graphics.DrawLine(dashed_pen, pts(i), pts(i + 1));
}
e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.HighQuality;
Pen bez_pen = new Pen(Color.Black, 3);
e.Graphics.DrawBezier(bez_pen, pts(0), pts(1), pts(2), pts(3))
}
Is there a way, or can someone help me with returning all the points that form the curve? I'd like for each point of a curve calculated from those points to be returned in an array of points, but I'm having no luck figuring it out, and haven't been able to find a similar solution on stackoverflow or google in general.
Thanks.
What you want to do is to convert a Bezier Curve (Cubic from the looks of it) into a Polyline
Use the Equation on this page...Value of t should be between 0 to 1...Calculate all values of Bx(t) and By(t) by using the equation for values of t in increments of "0, 0.01, 0.02....1" (Convert them to integers of course) The smaller your increments, the more accurate your points will be.
Here's a C Sample of the DeCasteljau Algorithm (almost the same procedure, but its a bit optimized i believe) :)
Perfect algorithm for creating smooth Bezier curve with optimal number of points is described by Maxim Shemanarev on Anti-Grain Geometry page: Adaptive Subdivision of Bezier Curves.
It may help if you use a lerp or float t derivatives in-between the draw bezier. I've found it helps with accuracy; considering the number of float calcs .
I know this is an old post, but, having found none of the current answers all that satisfying, hopefully others will get some use out of the following:
using System.Collections.Generic;
using System.Drawing;
public List<Point> CubicBezierToPoints(Point P0, Point P1, Point P2, Point P3, double step = 0.01)
{
var pointList = new List<Point>();
for (var t = 0.00; t <= 1; t += step)
{
var x = Math.Pow(1 - t, 3) * P0.X + 3 * Math.Pow(1 - t, 2) * t * P1.X +
3 * (1 - t) * Math.Pow(t, 2) * P2.X + Math.Pow(t, 3) * P3.X;
var y = Math.Pow(1 - t, 3) * P0.Y + 3 * Math.Pow(1 - t, 2) * t * P1.Y +
3 * (1 - t) * Math.Pow(t, 2) * P2.Y + Math.Pow(t, 3) * P3.Y;
pointList.Add(new Point((int)x,(int)y));
}
return pointList;
}