I have a list of Points that have been drawn on pictureBox1.
pictureBox1 has been transformed.
Now, I want to get XY coordinates of the point that was drawn as I hover over any drawn point.
When I hover over the pictureBox1, I am getting the XY of the pictureBox -- not a transformed XY.
Can you help me get to the transformed XY?
Thanks
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
int height = pictureBox1.ClientSize.Height / 2;
int width = pictureBox1.ClientSize.Width / 2;
//=====
//scale
//=====
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.TranslateTransform(-width, -height);
e.Graphics.ScaleTransform(2f, 2f);
//===========
//draw center
//===========
e.Graphics.DrawLine(new Pen(Color.Black, 0.5f), new Point(width - 2, height), new Point(width + 2, height));
e.Graphics.DrawLine(new Pen(Color.Black, 0.5f), new Point(width, height - 2), new Point(width, height + 2));
//===========
//draw points
//===========
foreach (var p in Points)
{
Point[] pts = new Point[] { new Point(p.X, p.Y) };
Rectangle rc = new Rectangle(pts[0], new Size(1, 1));
e.Graphics.DrawRectangle(Pens.Red, rc);
}
}
As a variation to #Vitaly's answer you can do this:
After transforming the Graphics object you can save its transformation matrix e.Graphics.Transform in a variable:
Matrix matrix = null;
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
int height = pictureBox1.ClientSize.Height / 2;
int width = pictureBox1.ClientSize.Width / 2;
//=====
//scale
//=====
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.TranslateTransform(-width, -height);
e.Graphics.ScaleTransform(2f, 2f);
matrix = e.Graphics.Transform; // save the transformation matrix!
...
This is necessary as the transfomation data are lost after the Paint event!
Note that the GraphicsState graphics.Save()&Restore() functions can't be used very well for this purpose, as it only puts the state on the stack for using it once, meaning it doesn't save these data in a persistent way.
Later you can use the Matrix and this function to either transform Points with the same matrix or reverse the transformation, e.g. for mouse coordinates:
PointF transformed(Point p0, bool forward)
{
Matrix m = matrix.Clone();
if (!forward) m.Invert();
var pt = new Point[] { p0 };
m.TransformPoints(pt);
return pt[0];
}
Now my MouseMove event shows the location both raw and re-transformed:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
label1.Text = e.Location + " <-> " + transformed(e.Location, false) ;
}
And to test the forward transformation you could add this to the end of the Paint event:
e.Graphics.ResetTransform();
for (int i = 0; i < Points.Count; i++)
{
Point[] pts = new Point[] { Point.Round(transformed(Points[i], true)) };
Rectangle rc = new Rectangle(pts[0], new Size(19, 19));
e.Graphics.DrawRectangle(Pens.Red, rc);
}
This first clears all the transformations and then paints larger Rectangles at the same locations by calling the transformed function.
Note that this will also work with a rotated Graphics object. (Although the last test does not draw the larger rectangles rotated, just moved to the right locations.)
Also note that I return PointF for better precision when scaling with fractions. You can use Point.Round (or Point.Truncate) to get Point.
Do have a look the the Matrix.Elements: They contain the numbers you have used:
float scaleX = matrix.Elements[0];
float scaleY = matrix.Elements[3];
float transX = matrix.Elements[4];
float transY = matrix.Elements[5];
Finally: It is well worth studying the many methods of Matrix..!
You can create a Matrix with necessary transformations and apply it in pictureBox1_Paint(...) via MultiplyTransform(...):
https://msdn.microsoft.com/en-us/library/bt34tx5d(v=vs.110).aspx
Then you can use Matrix::TransformPoints(...) to get transformed XY
Related
What I want to do is to create this rotating cone visual effect.
I had previously used DirectX for that.
What i have tried so far:
Even if I'm changing the thickness to 50 or more, the Arc is still not filled.
public partial class Form1 : Form
{
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
var center = new Point(pictureBox1.Width / 2, pictureBox1.Height / 2);
var innerR = 30;
var thickness = 20;
var startAngle = 0;
var arcLength = 360;
var outerR = innerR + thickness;
var outerRect = new Rectangle
(center.X - outerR, center.Y - outerR, 2 * outerR, 2 * outerR);
var innerRect = new Rectangle
(center.X - innerR, center.Y - innerR, 2 * innerR, 2 * innerR);
using (var p = new GraphicsPath())
{
p.AddArc(outerRect, startAngle, arcLength);
p.AddArc(innerRect, startAngle + arcLength, -arcLength);
p.CloseFigure();
e.Graphics.FillPath(Brushes.Green, p);
e.Graphics.DrawPath(Pens.Green, p);
}
}
}
I want to be able to fill the arc even when the thickness is 20 or less.
Or when the value of the innerR radius changes.
The goal is to be able to fill the arc in any case.
Here's one method of drawing that cone.
It looks like a Radar sweep, so you may want to define the sweep angle and the rotation speed (how much the current rotation angle is increased based on the Timer's interval).
Using a standard System.Windows.Forms.Timer to invalidate the Canvas that contains the Image you're showing here.
The Radar contour (the external perimeter) is centered on the canvas and drawn in relation to the thickness specified (so it's always sized as the canvas bounds). It doesn't necessarily be a perfect circle, it can be elliptical (as in the image here)
The Cone section is drawn adding an Arc to a GraphicsPath and is closed drawing two lines, from the center point of the outer GraphicsPath to the starting and ending points of the Arc (I think this is a simple method to generate a curved conic figure, it can be used in different situations and lets you generate different shapes almost without calculations, see the code about this)
It's filled with a LinearGradientBrush, the section near the center has less transparency than the section near the border; adjust as required
Each time the rotation angle reaches 360°, it's reset to 0.
This is delegated to the Timer's Tick event handler
=> Built with .Net 7, but if you need to adapt it to .Net Framework, the only things to change are the syntax of the using blocks, remove the null-forgiving operator from here: canvas!.ClientRectangle and nullable reference types (e.g., change object? to just object)
public partial class SomeForm : Form {
public SomeForm() {
InitializeComponent();
radarTimer.Interval = 100;
radarTimer.Tick += RadarTimer_Tick;
}
float coneSweepAngle = 36.0f;
float coneRotationAngle = .0f;
float radarSpeed = 1.8f;
float radarThickness = 5.0f;
System.Windows.Forms.Timer radarTimer = new System.Windows.Forms.Timer();
private void RadarTimer_Tick(object? sender, EventArgs e) {
coneRotationAngle += radarSpeed;
coneRotationAngle %= 360.0f;
canvas.Invalidate();
}
private void canvas_Paint(object sender, PaintEventArgs e) {
var center = new PointF(canvas.Width / 2.0f, canvas.Height / 2.0f);
RectangleF outerRect = canvas!.ClientRectangle;
outerRect.Inflate(-(radarThickness / 2.0f), -(radarThickness / 2.0f));
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using var pathOuter = new GraphicsPath();
using var pathInner = new GraphicsPath();
pathOuter.AddEllipse(outerRect);
pathInner.StartFigure();
pathInner.AddArc(outerRect, coneRotationAngle, coneSweepAngle);
var arcPoints = pathInner.PathPoints;
PointF first = arcPoints[0];
PointF last = arcPoints[arcPoints.Length - 1];
pathInner.AddLines(new[] { center, last, center, first });
pathInner.CloseFigure();
using var outerPen = new Pen(Color.FromArgb(100, Color.Red), radarThickness);
using var innerBrush = new LinearGradientBrush(
center, first, Color.FromArgb(200, Color.Orange), Color.FromArgb(20, Color.Orange));
e.Graphics.FillPath(innerBrush, pathInner);
e.Graphics.DrawPath(outerPen, pathOuter);
}
}
This is how it works:
I've been trying to solve a problem I'm having with rotating an oval. The code that I'm posting works, but it's mimicking the kind of code I have to work with for real. Meaning, I can't use the OnPaint override and I'm limited to what I can do in the main code. I'm adding an oval to a graphic layer, and I need to be able to rotate, move and resize the oval. Move and resizing work flawlessly, but rotating doesn't work as I need it to.
If you click in the small box at the 9 oclock position,
the oval will rotate as expected:
The required behavior is to be able to click in the small box at the 12 oclock position, and have the oval rotate again. This does not occur. In order to get the oval to rotate again you need to click in the original 9 oclock position. What I'm really, really trying to find out is how to get the coordinates of the box at the 12 oclock position (or what ever position or location that box ends up after rotating) so that I can rotate it again. Thus far, I have been unable to figure it out. Please try and understand, I'm working with old code that was poorly written and I'm not allowed to change very much of it. What I write must integrate with what's already there. Below is the code snippet that demonstrates what I'm doing. I know I'm missing something obvious, just don't know what. Thanks.
public partial class Form1 : Form
{
int theAngle = 0;
Pen pen2 = new Pen(Color.FromArgb(255, 68, 125, 255), 4);
Pen pen3 = new Pen(Color.Green, 4);
Pen smallPen = new Pen(Color.Black, 1);
PointF center = new PointF(0, 0);
Rectangle rectangle = new Rectangle(20, 20, 100, 30);
Rectangle myRect2 = new Rectangle();
bool mouseBtnDown = false;
Graphics gw;
public Form1()
{
InitializeComponent();
this.MouseDown += mouseDown;
gw = this.CreateGraphics();
}
private void mouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (myRect2.Contains(e.Location))
theAngle+=90;
rotate();
}
if (e.Button == MouseButtons.Right)
{
//oval = false;
//mouseBtnDown = false;
theAngle = 0;
rectangle.X = e.X - 50;
rectangle.Y = e.Y - 15;
rectangle.Width = 100;
rectangle.Height = 30;
center.X = rectangle.Left + (0.5f * rectangle.Width);
center.Y = rectangle.Top + (0.5f * rectangle.Height);
myRect2.Size = new Size(15, 15);
myRect2.Location = new Point(rectangle.Left - 15, (rectangle.Top - (rectangle.Height / 2)) + 15);
drawstuff();
// Invalidate();
}
}
public void rotate()
{
var matrix = new Matrix();
matrix.RotateAt(theAngle, center);
gw.Transform = matrix;
drawstuff();
}
public void drawstuff()
{
gw.SmoothingMode = SmoothingMode.AntiAlias; // Creates smooth lines.
gw.DrawEllipse(pen2, rectangle);
gw.DrawRectangle(smallPen, myRect2);
}
}
You can use the Transform matrix to rotate points. So what I've done is get the 4 corner points of myRect2, rotate them using the same Transform matrix, then assign these to a rectangle. You can then use this new rectangle to check the location. I also changed the call to drawstuff() at the end of the right button click to call rotate(), this way the rotated rectangle can get updated when the ellipse is first placed, and the graphics transform angle gets updated to 0.
public partial class Form1 : Form
{
int theAngle = 0;
Pen pen2 = new Pen(Color.FromArgb(255, 68, 125, 255), 4);
Pen pen3 = new Pen(Color.Green, 4);
Pen smallPen = new Pen(Color.Black, 1);
PointF center = new PointF(0, 0);
Rectangle rectangle = new Rectangle(20, 20, 100, 30);
Rectangle myRect2 = new Rectangle();
Rectangle rotatedRect2 = new Rectangle();
bool mouseBtnDown = false;
Graphics gw;
public Form1()
{
InitializeComponent();
this.MouseDown += mouseDown;
gw = this.CreateGraphics();
}
private void mouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (rotatedRect2.Contains(e.Location))
theAngle += 90;
rotate();
}
if (e.Button == MouseButtons.Right)
{
//oval = false;
//mouseBtnDown = false;
theAngle = 0;
rectangle.X = e.X - 50;
rectangle.Y = e.Y - 15;
rectangle.Width = 100;
rectangle.Height = 30;
center.X = rectangle.Left + (0.5f * rectangle.Width);
center.Y = rectangle.Top + (0.5f * rectangle.Height);
myRect2.Size = new Size(15, 15);
myRect2.Location = new Point(rectangle.Left - 15, (rectangle.Top - (rectangle.Height / 2)) + 15);
rotate();
//drawstuff();
// Invalidate();
}
}
public void rotate()
{
var matrix = new Matrix();
matrix.RotateAt(theAngle, center);
gw.Transform = matrix;
// Get the 4 corner points of myRect2.
Point p1 = new Point(myRect2.X, myRect2.Y),
p2 = new Point(myRect2.X + myRect2.Width, myRect2.Y),
p3 = new Point(myRect2.X, myRect2.Y + myRect2.Height),
p4 = new Point(myRect2.X + myRect2.Width, myRect2.Y + myRect2.Height);
Point[] pts = new Point[] { p1, p2, p3, p4 };
// Rotate the 4 points.
gw.Transform.TransformPoints(pts);
// Update rotatedRect2 with those rotated points.
rotatedRect2.X = pts.Min(pt => pt.X);
rotatedRect2.Y = pts.Min(pt => pt.Y);
rotatedRect2.Width = pts.Max(pt => pt.X) - pts.Min(pt => pt.X);
rotatedRect2.Height = pts.Max(pt => pt.Y) - pts.Min(pt => pt.Y);
drawstuff();
}
public void drawstuff()
{
gw.SmoothingMode = SmoothingMode.AntiAlias; // Creates smooth lines.
gw.DrawEllipse(pen2, rectangle);
gw.DrawRectangle(smallPen, myRect2);
}
}
Something to note. Drawing to the screen like this (using the form's created graphics and drawing using your own draw function) means the ellipses/rectangles are only drawn once. i.e. if you draw a few then minimize your form, when you bring it back up the ellipses will be gone. Not sure if this is what you're after or not. One way to fix this would be to draw the ellipses to a Bitmap and then in the form's Paint event this bitmap is draw to the form.
i need to generate a new method to fill the triangle in the below code and call it separately
any advise please?
public void draw(Graphics g, Pen blackPen)
{
double xDiff, yDiff, xMid, yMid;
xDiff = oppPt.X - keyPt.X;
yDiff = oppPt.Y - keyPt.Y;
xMid = (oppPt.X + keyPt.X) / 2;
yMid = (oppPt.Y + keyPt.Y) / 2;
// draw triangle
g.DrawLine(blackPen, (int)keyPt.X, (int)keyPt.Y, (int)(xMid + yDiff / 2), (int)(yMid - xDiff / 2));
g.DrawLine(blackPen, (int)(xMid + yDiff / 2), (int)(yMid - xDiff / 2), (int)oppPt.X, (int)oppPt.Y);
g.DrawLine(blackPen, (int)keyPt.X, (int)keyPt.Y, oppPt.X, oppPt.Y);
}
the method should take both of these arguments
public void fillTriangle(Graphics g, Brush redBrush)
{
}
Use a single function for the drawing, and for reduced complexity and consistency use a GraphicsPath object.
void DrawGraphics(Graphics g, Pen pen, Brush brush)
{
float xDiff=oppPt.X-keyPt.X;
float yDiff=oppPt.Y-keyPt.Y;
float xMid=(oppPt.X+keyPt.X)/2;
float yMid=(oppPt.Y+keyPt.Y)/2;
// Define path with the geometry information only
var path = new GraphicsPath();
path.AddLines(new PointF[] {
keyPt,
new PointF(xMid + yDiff/2, yMid-xDiff/2),
oppPt,
});
path.CloseFigure();
// Fill Triangle
g.FillPath(brush, path);
// Draw Triangle
g.DrawPath(pen, path);
}
The result is as seen below:
You just need to create an array with the dots, after that configure how the fill will be and then yes draw FillPolygon which is an entity to DrawPolygon which is just the outline.
public void draw(Pen blackPen)
{
Graphics draw = CreateGraphics();
Point[] points = new Point[6];
points[0].X = 0;
points[0].Y = 0;
points[1].X = 150;
points[1].Y = 150;
points[2].X = 0;
points[2].Y = 150;
using (SolidBrush fillvar = new SolidBrush(Color.FromArgb(100, Color.Yellow)))
{
draw.FillPolygon(fillvar, points.ToArray());
draw.DrawPolygon(Pens.DarkBlue, points);
}
}
If you want to draw the FillPolygon inside something, as with a PictureBox you just have to assign it to the Graphics draw.
Graphics draw = picturebox.CreateGraphics();
Above is just a practical illustration of how it works, take a look at your code. Missing just implement its xDiff, yiff, xMid, yMid coordinates.
public void draw(Graphics g, Pen blackPen)
{
double xDiff, yDiff, xMid, yMid;
Point[] points = new Point[6];
points[0].X = 50;
points[0].Y = 50;
points[1].X = 150;
points[1].Y = 150;
points[2].X = 0;
points[2].Y = 150;
SolidBrush varbrush = new SolidBrush(Color.FromArgb(100, Color.Yellow));
fillTriangle(g, varbrush, points);
}
You will have to pass the dots to fillTriangle and draw them in this method.
public void fillTriangle(Graphics g, Brush varbrush, Point[] points)
{
g.FillPolygon(varbrush, points.ToArray());
g.DrawPolygon(Pens.Red, points);
}
Imagine I have a line which is colored Gradient with three color : dark red, red and light red. I want to change position of these colors in that line . My purpose is showing something is moving along line.
I don't know How I can create animation for changing position of each colors in a line which is colored gradient.
I have found this : https://learn.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/how-to-animate-the-position-or-color-of-a-gradient-stop
but It isn't too clear.
Here is an example:
It uses a LineraGradientBrush, moving the starting point of the defining rectangle top left and painting a rotated rectangle onto a PictureBox:
Point p1 = Point.Empty;
private void timer1_Tick(object sender, EventArgs e)
{
int deltaX = -3;
int deltaY = -3;
p1 = new Point(p1.X + deltaX , p1.Y + deltaY); // roll..
if (p1.X < deltaX * 1000) p1 = Point.Empty; // ..around
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
float angle = 33f;
if (!timer1.Enabled) return;
Rectangle rectG = new Rectangle(p1.X, p1.Y, 122, 22);
Rectangle rectR = new Rectangle(22, 22, 222, 22);
LinearGradientBrush lBrush = new LinearGradientBrush(rectG,
Color.Red, Color.Red, angle, false);
ColorBlend cblend = new ColorBlend(5);
cblend.Colors = new Color[5]
{ Color.Red, Color.Pink, Color.MistyRose, Color.LightCoral, Color.White };
cblend.Positions = new float[5] { 0f, 0.2f, 0.5f, 0.8f, 1f };
lBrush.InterpolationColors = cblend;
lBrush.WrapMode = WrapMode.TileFlipXY;
e.Graphics.RotateTransform(angle);
e.Graphics.TranslateTransform(22,11);
e.Graphics.FillRectangle(lBrush, rectR);
}
Note that this being Winforms you can't get real smooth animations but if the control/form you paint on is DoubleBufered at least it won't flicker..
private void panel1_Paint(object sender, PaintEventArgs e)
{
Pen myPen = new Pen(Color.Blue, 1);
Pen myPen2 = new Pen(Color.Red, 1);
Point[] array = { new Point(639, 75), new Point(606, 124), new oint(664, 123) };
matrix.TransformPoints(array);
e.Graphics.Transform = matrix;
e.Graphics.RotateTransform(ang, MatrixOrder.Append);
myPen2.RotateTransform(ang, MatrixOrder.Append);
e.Graphics.DrawPolygon(myPen2, array);
}
I'm using Visual Studio 2010. The above code should be for drawing a triangle in C#, but I can't rotate it without drawn triangle location. How can I achieve that?
This will do the rotation:
private void panel1_Paint(object sender, PaintEventArgs e)
{
Pen myPen = new Pen(Color.Blue, 1);
Pen myPen2 = new Pen(Color.Red, 1);
Point[] array = { new Point(239, 75), new Point(206, 124), new Point(264, 123) };
float x = array.Select(_ => _.X).Sum() / array.Length;
float y = array.Select(_ => _.Y).Sum() / array.Length;
e.Graphics.DrawPolygon(myPen, array);
e.Graphics.TranslateTransform(x,y);
e.Graphics.RotateTransform(ang);
e.Graphics.TranslateTransform(-x, -y);
e.Graphics.DrawPolygon(myPen2, array);
}
No need to rotate a simple Pen although for more adavanced pens this may well be called for..
I have calculated the rotation center coordinates and then move the Graphics' origin there, rotate it and then move back. Then we can draw.
To test you can use a trackbar:
float ang = 0f;
private void trackBar1_Scroll(object sender, EventArgs e)
{
ang = (float) trackBar1.Value;
panel1.Invalidate();
}
You are using multiple methods mixed up. Don't rotate the pen/e.Graphics/matrix all together. When you call e.Graphics.RotateTransform you are manipulating the e.Graphics.Transform
You need to setup the matrix and assign it to the transform. In your case, your triangle has world coordinates, so you need to translate them before you can rotate them.
This will help:
public partial class Form1 : Form
{
// define triangle points ('world coords :'-( ?????????
private Point[] _triangle = { new Point(639, 75), new Point(606, 124), new Point(664, 123) };
// cache the angle
private float _angle = 0;
// cache the GObjects!!
private Pen _myPen = new Pen(Color.Blue, 1);
private Pen _myPen2 = new Pen(Color.Red, 1);
// The rotation origin position
private Point _origin = new Point(637, 110);
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
// draw the origin triangle
e.Graphics.DrawPolygon(_myPen, _triangle);
// create a matrix
Matrix matrix = new Matrix();
// first translate the triangle coordinates with the negative origin coords (translate coords to origin coordinate system)
// This translation is only needed, because your triangle is in world coordinates..
matrix.Translate(-_origin.X, -_origin.Y, MatrixOrder.Append);
// do the rotation..
matrix.Rotate(_angle, MatrixOrder.Append);
// translate the triangle coordinates back to the 'world' coordinate system
matrix.Translate(_origin.X, _origin.Y, MatrixOrder.Append);
// assign the matrix to the Graphics
e.Graphics.Transform = matrix;
// Draw the polygon
e.Graphics.DrawPolygon(_myPen2, _triangle);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
float.TryParse(textBox1.Text, NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture.NumberFormat, out _angle);
panel1.Refresh();
}
}
I would define the triangle with it's own origin, this way you can draw/rotate it anywhere on the panel.