I create a code give that allow me to resize a circle and move it
first mouse click give me the center for the circle.
the circle radius will change with the cursor movement (closer to the center smaller radius farther from the center bigger radius).
click second time the radius will not be changed and the circle will be finalized.
This is an image similar to what I want to do:
http://lh6.ggpht.com/_wQH6U92SY04/S_6lAJI7E-I/AAAAAAAAKwE/i-Jkq-nI5Ss/GoogleMapCircle%5B11%5D.gif?imgmax=800
The problems are :
the center is not exactly where I click the mouse first time.
the cursor should be exactly at the circle border when I move it.
the biggest problem is after clicking second time the circle is move farther from the center .
PLEASE HELP
using System;
using System.Drawing;
using System.Windows.Forms;
namespace project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
}
Bitmap background;
Graphics scG;
Rectangle rectangleObj;
int clikno = 0;
private Point clickCurrent = Point.Empty;
private Point clickPrev = Point.Empty;
private void Form1_Load(object sender, EventArgs e)
{
background = new Bitmap(this.Width, this.Height);
rectangleObj = new Rectangle(10, 10, 100, 100);
scG = Graphics.FromImage(background);
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
clickCurrent = this.PointToClient(Cursor.Position);
clickPrev = clickCurrent;
rectangleObj.X = e.X;
rectangleObj.Y = e.Y;
}
protected override void OnPaint(PaintEventArgs pe)
{
pe.Graphics.DrawImage(Draw(), 0, 0);
}
public Bitmap Draw()
{
Graphics scG = Graphics.FromImage(background);
Pen myPen = new Pen(System.Drawing.Color.Red, 3);
scG.Clear(SystemColors.Control);
scG.DrawEllipse(myPen, rectangleObj);
return background;
}
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
clikno = clikno + 1;
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
double oradius = Math.Sqrt((Math.Pow(clickPrev.X - e.X, 2)) + (Math.Pow(clickPrev.Y - e.Y, 2)));
int radius = Convert.ToInt32(oradius);
if (clikno == 1)
{
rectangleObj.Height = radius;
rectangleObj.Width = radius;
rectangleObj.X = clickPrev.X;
rectangleObj.Y = clickPrev.Y;
Refresh();
}
if (clikno == 2)
clikno = 0;
Refresh();
}
}
}
I figured it out
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace Project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
}
Bitmap background;
Graphics scG;
Rectangle rectangleObj;
Rectangle center;
int clikno = 0;
private Point clickCurrent = Point.Empty;
private Point clickPrev = Point.Empty;
private void Form1_Load(object sender, EventArgs e)
{
background = new Bitmap(this.Width, this.Height);//, this.Width,this.Height);
rectangleObj = new Rectangle(10, 10, 100, 100);
center = new Rectangle(10, 10, 3, 3);
scG = Graphics.FromImage(background);
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
clickCurrent = this.PointToClient(Cursor.Position);
clickPrev = clickCurrent;
if (clickPrev == Point.Empty) return;
Refresh();
}
protected override void OnPaint(PaintEventArgs pe)
{
pe.Graphics.DrawImage(Draw(), 0, 0);
}
public Bitmap Draw()
{
Graphics scG = Graphics.FromImage(background);
Pen myPen = new Pen(System.Drawing.Color.Red, 3);
scG.Clear(SystemColors.Control);
scG.DrawEllipse(myPen, rectangleObj);
// scG.DrawRectangle(myPen, rectangleObj);
scG.DrawEllipse(myPen, center);
return background;
}
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
clikno = clikno + 1;
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
double oradius = Math.Sqrt((Math.Pow(clickPrev.X - e.X, 2)) + (Math.Pow(clickPrev.Y - e.Y, 2)));
int radius = Convert.ToInt32(oradius);
if (clikno == 1)
{
rectangleObj.Height = radius;
rectangleObj.Width = radius;
rectangleObj.X = clickPrev.X- rectangleObj.Height /2;// +radius;
rectangleObj.Y = clickPrev.Y - rectangleObj.Width / 2;// +radius;
center.X = clickPrev.X - center.Height / 2;// +radius;
center.Y = clickPrev.Y - center.Width / 2;// +radius;
Refresh();
}
if (clikno == 2)
clikno = 0;
Refresh();
}
string myString = 5.ToString();
}
}
Related
I am trying to make a re-sizable square box with my mouse but if I drag my mouse fast it's very noticeable that it's offset from where it should be eg, http://imgur.com/a/sglGv (Red is where it should be, black is where it is.)
using System.Drawing;
using System.Windows.Forms;
using System;
using System.Drawing.Drawing2D;
namespace WindowsFormsApp6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TransparencyKey = Color.SaddleBrown;
canvas.MouseDown += new MouseEventHandler(canvas_MouseDown);
canvas.MouseUp += new MouseEventHandler(canvas_MouseUp);
canvas.MouseMove += new MouseEventHandler(canvas_MouseMove);
Load += new EventHandler(Form1_Load);
//typeof(Panel).InvokeMember("DoubleBuffered", BindingFlags.SetProperty| BindingFlags.Instance | BindingFlags.NonPublic, null,canvas, new object[] { true });
}
private Bitmap m_OriginalImage = null;
private int X0, Y0, X1, Y1;
private bool SelectingArea = false;
private Bitmap SelectedImage = null;
private Graphics SelectedGraphics = null;
private void Form1_Load(object sender, EventArgs e)
{
m_OriginalImage = new Bitmap(canvas.Image);
KeyPreview = true;
}
private void canvas_MouseDown(object sender, MouseEventArgs e)
{
SelectingArea = true;
X0 = e.X;
Y0 = e.Y;
SelectedImage = new Bitmap(m_OriginalImage);
SelectedGraphics = Graphics.FromImage(SelectedImage);
canvas.Image = SelectedImage;
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
if (!SelectingArea) return;
X1 = e.X;
Y1 = e.Y;
SelectedGraphics.DrawImage(m_OriginalImage, 0, 0);
using (Pen select_pen = new Pen(Color.Red))
{
select_pen.DashStyle = DashStyle.Dash;
Rectangle rect = MakeRectangle(X0, Y0, X1, Y1);
//ControlPaint.DrawReversibleFrame(rect,this.BackColor, FrameStyle.Dashed);
SelectedGraphics.DrawRectangle(select_pen, rect);
}
canvas.Refresh();
}
private void canvas_MouseUp(object sender, MouseEventArgs e)
{
if (!SelectingArea) return;
SelectingArea = false;
SelectedImage = null;
SelectedGraphics = null;
canvas.Image = m_OriginalImage;
canvas.Refresh();
Rectangle rect = MakeRectangle(X0, Y0, X1, Y1);
if ((rect.Width > 0) && (rect.Height > 0))
{
MessageBox.Show(rect.ToString());
}
}
private Rectangle MakeRectangle(int x0, int y0, int x1, int y1)
{
return new Rectangle(
Math.Min(x0, x1),
Math.Min(y0, y1),
Math.Abs(x0 - x1),
Math.Abs(y0 - y1));
}
}
}
I have tried everything I could think from timers to threads.
Any suggestions to keep it at 60 fps would be appreciated greatly.
Lately I found out how to rotate images and I already have problem.
Here is piece of code that I have problem with but you probably don't need to look at it anyway...
Graphics g = e.Graphics;
g.TranslateTransform((float)Width / 2, (float)Height / 2);
g.RotateTransform(myAngle);
Brush brush = new SolidBrush(Color.FromArgb(32, 1, 1, 1));
Pen pen = new Pen(Color.FromArgb(255, 128 , 128, 128), 3);
g.FillRectangle(brush, nX, nY, snX - nX, snY - nY);
g.DrawRectangle(pen, nX, nY, snX - nX, snY - nY);
variables X , sX , snX, Y , sY, snY are coordinates of mouse in specific moments and are calculated mostly in Form1_MouseMove and I can't show what's in there.
How can I make these variables also change no matter what myAngle is?
I've made an example, how to draw on a rotated bitmap: (using a picturebox/bitmap/trackbar)
public partial class Form1 : Form
{
private Bitmap _bitmap;
public Form1()
{
InitializeComponent();
_bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
}
private void TransformGraphics(Graphics g)
{
g.ResetTransform();
g.TranslateTransform(_bitmap.Width / 2, _bitmap.Height / 2);
g.RotateTransform(trackBar1.Value);
g.TranslateTransform(-_bitmap.Width / 2, -_bitmap.Height / 2);
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
TransformGraphics(e.Graphics);
e.Graphics.DrawImage(_bitmap, new Point());
}
private Point? _previousPoint;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
_previousPoint = e.Location;
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
_previousPoint = null;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (_previousPoint.HasValue)
{
using (Graphics g = Graphics.FromImage(_bitmap))
{
TransformGraphics(g);
var matrix = g.Transform;
matrix.Invert();
var points = new[] { _previousPoint.Value, e.Location };
matrix.TransformPoints(points);
g.ResetTransform();
g.DrawLine(Pens.Black, points[0], points[1]);
pictureBox1.Invalidate();
_previousPoint = e.Location;
}
}
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
pictureBox1.Invalidate();
}
}
You can add another trackbar for scaling.
I' ve drawn roundRectangle using Graphics Path OnPaintEvent
and I already added mouseevent to know if cursor was over the g.p .
void Round_MouseMove(object sender, MouseEventArgs e)
{
Point mousePt = new Point(e.X, e.Y);
if (_path != null)
if (_path.IsVisible(e.Location))
MessageBox.Show("GraphicsPath has been hovered!");
}
Question: is there a way to resize or redraw(hide previous then draw new) a graphicsPath runtime?
Invoke Invalidate for redrawn the Form, so the OnPaint(PaintEventArgs e) will be executed.
Check the following example:
public sealed partial class GraphicsPathForm : Form
{
private bool _graphicsPathIsVisible;
private readonly Pen _pen = new Pen(Color.Red, 2);
private readonly Brush _brush = new SolidBrush(Color.FromArgb(249, 214, 214));
private readonly GraphicsPath _graphicsPath = new GraphicsPath();
private Rectangle _rectangle = new Rectangle(10, 30, 100, 100);
public GraphicsPathForm()
{
InitializeComponent();
_graphicsPath.AddRectangle(_rectangle);
}
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.Bilinear;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawPath(_pen, _graphicsPath);
if (_graphicsPathIsVisible)
g.FillPath(_brush, _graphicsPath);
base.OnPaint(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
var isVisible = _graphicsPath.IsVisible(e.Location);
if (isVisible == _graphicsPathIsVisible)
return;
const int zoom = 5;
if (isVisible)
{
if (!_graphicsPathIsVisible)
{
_rectangle.Inflate(zoom, zoom);
_graphicsPath.Reset();
_graphicsPath.AddRectangle(_rectangle);
}
}
else
{
if (_graphicsPathIsVisible)
{
_rectangle.Inflate(-zoom, -zoom);
_graphicsPath.Reset();
_graphicsPath.AddRectangle(_rectangle);
}
}
_graphicsPathIsVisible = isVisible;
Invalidate();
base.OnMouseMove(e);
}
}
I hope it helps.
This is the code:
private void hsMagnfier_OnMouseDown(object sender)
{
int x = mLastCursorPosition.X;
int y = mLastCursorPosition.Y;
MagnifierForm magnifier = new MagnifierForm(mConfiguration, System.Windows.Forms.Cursor.Position);//mLastCursorPosition);
magnifier.Show();
}
This code above is in a Form which I can drag over the screen.
Then when I click on an icon it's doing the magnifier.Show(); and the magnifier form is shown up where the mouse current position is.
But if I click on it again so now the position of the new form the magnifier is in my Form1 center. And not where the mouse current position as in the first time.
This is the MagnifierForm code maybe first time it's in the current mouse position but in the next time/s it's in the center of Form1 ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
namespace ScreenVideoRecorder
{
public partial class MagnifierForm : Form
{
public MagnifierForm(Configuration configuration, Point startPoint)
{
InitializeComponent();
//--- My Init ---
mConfiguration = configuration;
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = mConfiguration.ShowInTaskbar;
TopMost = mConfiguration.TopMostWindow;
Width = mConfiguration.MagnifierWidth;
Height = mConfiguration.MagnifierHeight;
// Make the window (the form) circular
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(ClientRectangle);
Region = new Region(gp);
mImageMagnifier = Properties.Resources.magnifierGlass;
mTimer = new Timer();
mTimer.Enabled = true;
mTimer.Interval = 20;
mTimer.Tick += new EventHandler(HandleTimer);
mScreenImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
mStartPoint = startPoint;
mTargetPoint = startPoint;
if (mConfiguration.ShowInTaskbar)
ShowInTaskbar = true;
else
ShowInTaskbar = false;
}
protected override void OnShown(EventArgs e)
{
RepositionAndShow();
}
private delegate void RepositionAndShowDelegate();
private void RepositionAndShow()
{
if (InvokeRequired)
{
Invoke(new RepositionAndShowDelegate(RepositionAndShow));
}
else
{
// Capture the screen image now!
Graphics g = Graphics.FromImage(mScreenImage);
g.CopyFromScreen(0, 0, 0, 0, new Size(mScreenImage.Width, mScreenImage.Height));
g.Dispose();
if (mConfiguration.HideMouseCursor)
Cursor.Hide();
else
Cursor = Cursors.Cross;
Capture = true;
if (mConfiguration.RememberLastPoint)
{
mCurrentPoint = mLastMagnifierPosition;
Cursor.Position = mLastMagnifierPosition;
Left = (int)mCurrentPoint.X - Width / 2;
Top = (int)mCurrentPoint.Y - Height / 2;
}
else
{
mCurrentPoint = Cursor.Position;
}
Show();
}
}
void HandleTimer(object sender, EventArgs e)
{
float dx = mConfiguration.SpeedFactor * (mTargetPoint.X - mCurrentPoint.X);
float dy = mConfiguration.SpeedFactor * (mTargetPoint.Y - mCurrentPoint.Y);
if (mFirstTime)
{
mFirstTime = false;
mCurrentPoint.X = mTargetPoint.X;
mCurrentPoint.Y = mTargetPoint.Y;
Left = (int)mCurrentPoint.X - Width / 2;
Top = (int)mCurrentPoint.Y - Height / 2;
return;
}
mCurrentPoint.X += dx;
mCurrentPoint.Y += dy;
if (Math.Abs(dx) < 1 && Math.Abs(dy) < 1)
{
mTimer.Enabled = false;
}
else
{
// Update location
Left = (int)mCurrentPoint.X - Width / 2;
Top = (int)mCurrentPoint.Y - Height / 2;
mLastMagnifierPosition = new Point((int)mCurrentPoint.X, (int)mCurrentPoint.Y);
}
Refresh();
}
protected override void OnMouseDown(MouseEventArgs e)
{
mOffset = new Point(Width / 2 - e.X, Height / 2 - e.Y);
mCurrentPoint = PointToScreen(new Point(e.X + mOffset.X, e.Y + mOffset.Y));
mTargetPoint = mCurrentPoint;
mTimer.Enabled = true;
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (mConfiguration.CloseOnMouseUp)
{
Close();
mScreenImage.Dispose();
}
Cursor.Show();
Cursor.Position = mStartPoint;
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mTargetPoint = PointToScreen(new Point(e.X + mOffset.X, e.Y + mOffset.Y));
mTimer.Enabled = true;
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if (mConfiguration.DoubleBuffered)
{
// Do not paint background (required for double buffering)!
}
else
{
base.OnPaintBackground(e);
}
}
protected override void OnPaint(PaintEventArgs e)
{
if (mBufferImage == null)
{
mBufferImage = new Bitmap(Width, Height);
}
Graphics bufferGrf = Graphics.FromImage(mBufferImage);
Graphics g;
if (mConfiguration.DoubleBuffered)
{
g = bufferGrf;
}
else
{
g = e.Graphics;
}
if (mScreenImage != null)
{
Rectangle dest = new Rectangle(0, 0, Width, Height);
int w = (int)(Width / mConfiguration.ZoomFactor);
int h = (int)(Height / mConfiguration.ZoomFactor);
int x = Left - w / 2 + Width / 2;
int y = Top - h / 2 + Height / 2;
g.DrawImage(
mScreenImage,
dest,
x, y,
w, h,
GraphicsUnit.Pixel);
}
if (mImageMagnifier != null)
{
g.DrawImage(mImageMagnifier, 0, 0, Width, Height);
}
if (mConfiguration.DoubleBuffered)
{
e.Graphics.DrawImage(mBufferImage, 0, 0, Width, Height);
}
}
//--- Data Members ---
#region Data Members
private Timer mTimer;
private Configuration mConfiguration;
private Image mImageMagnifier;
private Image mBufferImage = null;
private Image mScreenImage = null;
private Point mStartPoint;
private PointF mTargetPoint;
private PointF mCurrentPoint;
private Point mOffset;
private bool mFirstTime = true;
private static Point mLastMagnifierPosition = Cursor.Position;
#endregion
}
}
The first time the new Form the magnifier is shown up where my mouse cursour is.
The next time i click on it's showing the magnifier form in the center of Form1 and not where the mouse cursour is.
Why is that ? When i clikc on the icon again it's still doing the
System.Windows.Forms.Cursor.Position
Again. Strange.
Consider you have two forms - Master and Child
If you are calling Child from Master on MouseUp event(for example), write the code in MouseUp event of Master form
ChildForm obj=new ChildForm();
obj.pntLocation = new Point(Cursor.Position.X, Cursor.Position.Y);
obj.ShowDialog();
Declare a variable inside the Child for location
public Point pntLocation;
Now set location inside the Form_Load of Child
this.Location = pntLocation;
Ok found that the part that doing it is here in the Magnifier form:
mConfiguration.RememberLastPoint = false;
if (mConfiguration.RememberLastPoint)
{
mCurrentPoint = mLastMagnifierPosition;
Cursor.Position = mLastMagnifierPosition;
Left = (int)mCurrentPoint.X - Width / 2;
Top = (int)mCurrentPoint.Y - Height / 2;
}
else
{
mCurrentPoint = Cursor.Position;
}
So I added for now the line: mConfiguration.RememberLastPoint = false; which did the job for now.
**i draw ellipse at runtime using following code.in that code i used graphics path for drawing(actually this is project requirement )and used widen method for graphics path.
but it gives runtime exception "out of memory".can i use this method in the case of ellipse?
while using widen method in the case of drawing rectangle at runtime, its working properly.
please solve this problem and give me some suggestion?**
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
Rectangle r;
bool isDown = false;
int initialX;
int initialY;
bool IsDrowing =true;
GraphicsPath gp1;
GraphicsPath gp2;
GraphicsPath gp3;
GraphicsPath gp;
Graphics g;
bool contained;
bool containedE;
bool containedC;
private void Form2_MouseDown(object sender, MouseEventArgs e)
{
isDown = true;
IsDrowing = true;
initialX = e.X;
initialY = e.Y;
}
private void Form2_MouseMove(object sender, MouseEventArgs e)
{
//IsDrowing = true;
if (isDown == true)
{
int width = e.X - initialX, height = e.Y - initialY;
r = new Rectangle(Math.Min(e.X, initialX),
Math.Min(e.Y, initialY),
Math.Abs(e.X - initialX),
Math.Abs(e.Y - initialY));
this.Invalidate();
}
}
private void Form2_Paint(object sender, PaintEventArgs e)
{
g = this.CreateGraphics();
gp = new GraphicsPath();
Pen pen = new Pen(Color.Red);
gp.AddEllipse(r);
gp.Widen(pen);
pen.DashStyle = DashStyle.Dash;
if (IsDrowing)
{
g.DrawPath(pen, gp);
}
private void Form2_MouseUp(object sender, MouseEventArgs e)
{
IsDrowing = false;
this.Refresh();
}
}
Basically: Avoid the GraphicsPath.Widen Method. It's buggy, search for "spirograph bug"
In your case this manifests because you try to widen a 0 by 0 rectangle. Modify your code like this:
private void Form2_Paint(object sender, PaintEventArgs e)
{
if (IsDrowing)
{
g = e.Graphics;
gp = new GraphicsPath();
gp.AddEllipse(r);
gp.Widen(new Pen(Color.Red, 10));
Pen pen = new Pen(Color.Red, 1);
pen.DashStyle = DashStyle.Dash;
g.DrawPath(pen, gp);
}
}
It may need additional work, but avoid the widening of an empty rectangle/ellipse.