Drawing an I-Beam based on two points - c#

I have two Point structures and I need to draw an I-Beam based on those points, where each point represents the cross-section on either side of the I-Beam. The width of the end caps should be fixed and arbitrary.
Basically I need to draw three lines. First I'll DrawLine(Point1, Point2), then I need the math to figure out how to draw the next two lines on perpendicular angles so that they are centered on Point1 and Point2.
The image below shows what I need to draw based on the center line. However, this line can be at any angle. The Point1 and Point2 that connect the line can be anywhere in a 2D space.

You can try playing around with LineCaps:
protected void DrawIBeam(Graphics g, Point fromPoint, Point toPoint)
{
using (GraphicsPath hPath = new GraphicsPath())
{
hPath.AddLine(new Point(-5, 0), new Point(5, 0));
CustomLineCap myCap = new CustomLineCap(null, hPath);
myCap.SetStrokeCaps(LineCap.Round, LineCap.Round);
using (Pen myPen = new Pen(Color.Black, 2))
{
myPen.CustomStartCap = myCap;
myPen.CustomEndCap = myCap;
g.DrawLine(myPen, fromPoint, toPoint);
}
}
}
and call it:
DrawIBeam(e.Graphics, new Point(10, 10), new Point(60, 60));
From CustomLineCap Class

Assuming a width that's half the width of the I part of the I beam, first you find the slope of the first line you drew.
Next, you take the negative inverse of the slope, and draw a line from Point1 of length width in both directions. That's why width is half of the width you want to draw.
Finally you draw a line from Point 2 of length width in both directions.
Here's the mathematical formula for drawing a perpendicular line.

Related

Draw rotated text in c#

I have a radar chart in chart.js in which I want to draw the labels as rotated. As I could see inthe doc, it is not possible, so I am trying to do it myself using basic drawing in c#. Here is the code I use :
Bitmap objBmpImage = new Bitmap(1000, 1000);
System.Drawing.Font objFont = new System.Drawing.Font("Arial", 12,
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
Graphics objGraphics = Graphics.FromImage(objBmpImage);
objGraphics.Clear(Color.Transparent);
float angle = (float)360.0 / (float)competences.Count();
objGraphics.TranslateTransform(500, 450);
objGraphics.RotateTransform(-90 - (angle / 3));
foreach (T_Ref_Competence competence in competences)
{
byte r, g, b;
HexToInt(competence.T_Ref_CompetenceNiveau2.T_Ref_CompetenceNiveau1.Couleur,
out r, out g, out b);
Brush brush = new System.Drawing.SolidBrush(Color.FromArgb(255,r,g,b));
objGraphics.DrawString(competence.Nom,objFont, brush, 255,0);
objGraphics.RotateTransform(angle);
}
string filename = Server.MapPath("..\\TempImage\\") + NomUtilisateur + ".png";
objBmpImage.Save(filename,System.Drawing.Imaging.ImageFormat.Png);
HexToInt is just a simple function that takes a #FF0000 and convert it to 3 bytes variables (255,0 and 0 for this exemple).
Here is the result so far :
As you can see, I can get something quite nice. However, I have one last request, which I am pretty sure is possible, but I'm not certain how.
How can I rotate the text 180 degrees for label on the left section ? In this exemple, from "Organisation" to "Vérification qualité et inspection". Mind you, I know how to decide which one I have to turn around, I don't know how to do it.
Thanks.
Idea:
Add 180 degrees to the angle.
Now the labels appear on the wrong side but have the right orientation. Move them by the diameter + textLength to the left. You can do so by providing a negative X to the DrawString call. No need for another transformation.
You can calculate the text length with the Graphics.MeasureString Method.

How can I determine if a rectangle intersects a right angle triangle?

I am trying to determine whether a rectangle intersects a triangle given the following triangle criteria:
the triangle will always be a right angle
the triangle will always derive from one of the corners of a rectangle
the triangle will always be the full width and height of the source rectangle
So one of my triangles can only be the top-left, top-right, bottom-left and bottom-right pieces of a rectangle.
Code would look similar to this:
Rectangle triangleSourceRect = new Rectangle(10, 10, 40, 40);
// top-left triangle from triangleSourceRect
Point[] topLeft = new Point[] {new Point(triangleSourceRect.Left,
triangleSourceRect.Top),
new Point(triangleSourceRect.Left,
triangleSourceRect.Bottom),
new Point(triangleSourceRect.Right,
triangleSourceRect.Top)};
Rectangle bounds = new Rectangle(28, 28, 20, 10);
if (bounds.Intersects(topLeft))
return true;
This is a diagram of the above code:

find the center point of coordinate 2d array c#

Is there a formula to average all the x, y coordinates and find the location in the dead center of them.
I have 100x100 squares and inside them are large clumps of 1x1 red and black points, I want to determine out of the red points which one is in the middle.
I looked into line of best fit formulas but I am not sure if this is what I need.
Sometimes all the red will be on one side, or the other side. I want to essentially draw a line then find the center point of that line, or just find the center point of the red squares only. based on the 100x100 grid.
List<Point> dots = new List<Point>();
int totalX = 0, totalY = 0;
foreach (Point p in dots)
{
totalX += p.X;
totalY += p.Y;
}
int centerX = totalX / dots.Count;
int centerY = totalY / dots.Count;
Simply average separately the x coordinates and the y coordinates, the result will be the coordinates of the "center".
What if there are two or more subsets of red points ? Do you want the black point inside them?
Otherwis, if I understood your question, just give a weight of 1 to red points and 0 to blacks. Then do the weighted mean on X and Y coordinate

Updating four points to stay in a Rectangle shape when one is moved

I am trying to draw a rectangular object that allows the user to click on a corner-point to resize and also rotate the rectangle in a 2D space.
Therefore I am using an array of four points ordered A, B, C, D (or 0, 1, 2, 3) from top-left to bottom-left in clockwise order.
The rotation works fine, I calculate the center point and rotate each point around it by an angle.
The resizing is done by determining which point was pressed down, and then setting its new position to the position of the mouse on each MouseMove event. The two adjacent points then need to be updated to stay in a rectangular shape. The resizing is intermittently not working. I have tried many ways to error-check, but all leave me with the same problem where if I move the mouse back and forth over the opposing point while moving a point, the points get distorted and are no longer a rectangular shape.
SOURCE CODE HERE
https://www.assembla.com/code/moozhe-testing/subversion/nodes/rotateRectangle
EXERPT OF PROBLEM CODE
private void MovePoint(int id, PointF newPoint)
{
PointF oldPoint = points[id];
PointF delta = newPoint.Substract(oldPoint);
PointF pointPrevious = points[(id + 3) % 4];
PointF pointNext = points[(id + 1) % 4];
PointF sidePrevious = pointPrevious.Substract(oldPoint);
PointF sideNext = pointNext.Substract(oldPoint);
PointF previousProjection = Projection(delta, sidePrevious);
PointF nextProjection = Projection(delta, sideNext);
pointNext = pointNext.AddPoints(previousProjection);
pointPrevious = pointPrevious.AddPoints(nextProjection);
points[(id + 3) % 4] = pointPrevious;
points[(id + 1) % 4] = pointNext;
points[id] = newPoint;
}
private PointF Projection(PointF vectorA, PointF vectorB)
{
PointF vectorBUnit = new PointF(vectorB.X, vectorB.Y);
vectorBUnit = vectorBUnit.Normalize();
float dotProduct = vectorA.X * vectorBUnit.X + vectorA.Y * vectorBUnit.Y;
return vectorBUnit.MultiplyByDecimal(dotProduct);
}
It sounds like you might want to be using a transformation matrix, instead of updating X/Y coordinates manually. Please check out this link:
Comparing GDI mapping modes with GDI+ transforms
Here's the MSDN reference:
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.transform

Graphic transformations

I'm working with data (stuff like Sin/Cosin waves, etc) that repeat with frequency M.
I've written a simple display control where it takes the data and paints connected lines to represent the data in a pretty picture.
My question is, the data is given where if painted onto a bitmap, quadrant 1 data is in quadrant 3 and quadrant 2 data is in quadrant 4 (and vice versa).
The bitmap is of width M and hight array.Max - array.Min.
Is there a simple transform for changing the data so it will display in the appropriate quadrants?
A good way of thinking about it is that (0,0) in world coordinates is divided between
(0,0), (width, 0), (0,height), (width, height)
which would (width/2, height/2) in image coordinates.
From there, the transform would be:
Data(x,y) => x = ABS(x - (width/2)), y = ABS(y - (Height/2))
Graphics.ScaleTransform is not a good idea because it will affect not only layout but also drawing itself (thickness of strokes, texts and so on).
I suggest you to prepare points list and then perform a transformation to them using the Matrix class. This is a small example I made for you, hope it will be helpful.
private PointF[] sourcePoints = GenerateFunctionPoints();
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.Clear(Color.Black);
// Wee need to perform transformation on a copy of a points array.
PointF[] points = (PointF[])sourcePoints.Clone();
// The way to calculate width and height of our drawing.
// Of course this operation may be performed outside this method for better performance.
float drawingWidth = points.Max(p => p.X) - points.Min(p => p.X);
float drawingHeight = points.Max(p => p.Y) - points.Min(p => p.Y);
// Calculate the scale aspect we need to apply to points.
float scaleAspect = Math.Min(ClientSize.Width / drawingWidth, ClientSize.Height / drawingHeight);
// This matrix transofrmation allow us to scale and translate points so the (0,0) point will be
// in the center of the screen. X and Y axis will be scaled to fit the drawing on the screen.
// Also the Y axis will be inverted.
Matrix matrix = new Matrix();
matrix.Scale(scaleAspect, -scaleAspect);
matrix.Translate(drawingWidth / 2, -drawingHeight / 2);
// Perform a transformation and draw curve using out points.
matrix.TransformPoints(points);
e.Graphics.DrawCurve(Pens.Green, points);
}
private static PointF[] GenerateFunctionPoints()
{
List<PointF> result = new List<PointF>();
for (double x = -Math.PI; x < Math.PI; x = x + 0.1)
{
double y = Math.Sin(x);
result.Add(new PointF((float)x, (float)y));
}
return result.ToArray();
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
Invalidate();
}
Try to invert the y-axis using
g.ScaleTransform(1, -1);
Also remember that for drawing in a scaled context, if you have to, Pen for example takes width as Single in some of its constructors, meaning inversely proportional fractional values can be used to make an invariant compensation for the effect of ScaleTransform.
UPDATE: forget that, Pen has its own local ScaleTransform, so both x an y can be compensated for.

Categories