Dragging graphics objects on top of bitmaps - c#

I am attempting to drag a shape around a picturebox on the mousemove event but am struggling to get it to move smoothly. The picture box has an image loaded as the background and I would like the graphics object to drag a circle on top of the image when the mouse is clicked and dragged.
I have it working by creating a clone of the original image each time the mouse moves and reloading the picture box but it seems like their must be a better way to achieve this.
Without reloading the original bitmap each time any graphics added remain on the image creating a trail which is more like a paint application.
How do I clear previous drawings without reloading the entire image each time? Any help appreciated.
private void picCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (_drag)
{
picCanvas.Image = (Bitmap)_original.Clone();
Graphics g = Graphics.FromImage((Bitmap)picCanvas.Image);
g.DrawEllipse(_whitePen, e.X, e.Y, 10, 10);
picCanvas.Invalidate();
}
}
private void picCanvas_MouseDown(object sender, MouseEventArgs e)
{
_drag = true;
}
private void picCanvas_MouseUp(object sender, MouseEventArgs e)
{
_drag = false;
}

check this sample it is simpler
//Load Image
Bitmap TestImage = new Bitmap(FileName);
//Create Graphics Object
Graphics g = Graphics.FromImage(TestImage);
g.DrawEllipse(new Pen(Color.Red), i, j,0.5F, 0.5F);
//View Your Results
pictureBox1.Image = TestImage;

To solve the problem in the best way, use picCanvas.Paint event.
Set the positions at mousemove event and use that positions to draw at paint event.
Point pos = Point.Empty;// or your initial position
private void picCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (_drag)
{
pos = e.Location;
}
}
private void picCanvas_Paint(object sender, PaintEventArgs e)
{
if (_drag)
{
Graphics g = e.Graphics;//The event handler sends us the graphics object to use for painting
g.DrawEllipse(_whitePen, pos.X, pos.Y, 10, 10);
}
}
You should add the Paint event to the Control and set the image at formload or some initialization function.
picCanvas.Image = (Bitmap)_original.Clone();

Using the above answer from Honibis I ended up with this.
load in the image and invalidate the picture to cause a refresh
picCanvas.Image = image;
picCanvas.Invalidate()
then in the paint event
private void picCanvas_Paint(object sender, PaintEventArgs e)
{
if (_drag)
{
using (Pen pen = new Pen(Color.White, 2))
{
e.Graphics.DrawEllipse(pen, pos.X, pos.Y, 10, 10);
}
}
}

Related

How to fix the delay between mouse wheel up and down on the picture box refresh while scaling a rectangle or a shape on the GraphicsPath object in C#?

1.I'm trying to scale a rectangle while a user does mouse up and mouse down on the picture box.
2.After doing 5 mouse wheel up and if you do mouse wheel down the rectangle still keeps scales up(expands).
3.Any solution to it?
GraphicsPath path=new GraphicsPath();
private float scale=1.0F;
private bool ActiveWheel=false;
public Form1()
{
path.AddRectangle(new Rectangle(10,10,50,100));
}
private void PictureBox1_Paint(object sender,PaintEventArgs e)
{
if(ActiveWheel)
{
ActiveWheel=false;
ScaleRectangle(e);
}
else
{
e.Graphics.DrawPath(Pens.Red,path);
}
}
private void PictureBox1_MouseWheel(object sender,MouseEventArgs e)
{
ActiveWheel=true;
scale=Math.Max(scale+Math.Sign(e.Delta)*0.1F,0.1F);
pictureBox1.Refresh();
}
}
private void ScaleRectangle(PaintEventArgs e)
{
var matrix=new Matrix();
matrix.Scale(scale,scale,MatrixOrder.Append);
path.Transform(matrix);
e.Graphics.DrawPath(Pens.Blue,path);
}
Any solution or idea how to scale down or scale up a shape suddenly without a delay in between mouse wheel ups and mouse wheel downs(see 2. if want to see actually o/p).
Just adjust the scale value in the MouseWheel() event, then ScaleTransform() the GRAPHICS surface (not the Path itself) in the Paint() event and draw:
public partial class Form1 : Form
{
private GraphicsPath path = new GraphicsPath();
private float scale = 1.0F;
public Form1()
{
InitializeComponent();
path.AddRectangle(new Rectangle(10, 10, 50, 100));
pictureBox1.MouseWheel += PictureBox1_MouseWheel;
pictureBox1.Paint += pictureBox1_Paint;
}
private void PictureBox1_MouseWheel(object sender, MouseEventArgs e)
{
scale = Math.Max(scale + Math.Sign(e.Delta) * 0.1F, 0.1F);
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.ScaleTransform(scale, scale);
e.Graphics.DrawPath(Pens.Red, path);
}
}
--- EDIT ---
It scales entirely, could you show me how to scale only graphics path
object and top, left have to be fixed, meaning without scaling the
top, left point?
In that case, translate to the top left point of your rectangle, scale, then translate back to the origin. Now draw your UNCHANGED rectangle:
private void PictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.TranslateTransform(10, 10);
e.Graphics.ScaleTransform(scale, scale);
e.Graphics.TranslateTransform(-10, -10);
e.Graphics.DrawPath(Pens.Red, path);
}
If you have other elements that are being drawn at different positions and/or scales, then you can reset the graphics surface before and after (each "element" can do the same type of thing to position itself and scale itself):
private void PictureBox1_Paint(object sender, PaintEventArgs e)
{
// possibly other drawing operations
e.Graphics.ResetTransform();
e.Graphics.TranslateTransform(10, 10);
e.Graphics.ScaleTransform(scale, scale);
e.Graphics.TranslateTransform(-10, -10);
e.Graphics.DrawPath(Pens.Red, path);
e.Graphics.ResetTransform();
// possibly other drawing operations
}
This approach is nice as it keeps the original information about your rectangle; the change is simply visual.

Why isn't my application drawing anything?

I'm very new(read 3 weeks exp) to C#(programming in general),started with html/css and javascript and now on my way with C#.
I'm trying to make my own simple 'Paint' application in windows form. But i've encountered an issue and just cant wrap my head around it, doesnt matter how much i read or follow other mans code, i'm stuck. The following code works fine but when resizing the application window the drawing dissappears.
As a solution ive read that declaring the Graphics method within the panel1_Paint event this should be resolved And here is my issue. See last code sample, ive come up with this(yes like i said, im new to this)and its not drawing anything.
ive simply tried to recreate the first example under the panel1_Paint event but i guess something went wrong during the mouseMove event and i cant figure out what it is.
Could someone explain to me what i am missing here, that would be very appreciated. thanks in advance.
[Old code]
namespace Painter
{
public partial class Form1 : Form
{
Graphics graphics;
Pen pen = new Pen(Color.Black, 1);
Point startingPoint = new Point(0, 0);
Point endPoint = new Point(0, 0);
bool mousePaint = false;
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
startingPoint = e.Location;
if (e.Button == MouseButtons.Left)
{
mousePaint = true;
}
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if(mousePaint == true)
{
endPoint = e.Location;
graphics = panel1.CreateGraphics();
graphics.DrawLine(pen, startingPoint, endPoint);
}
startingPoint = endPoint;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
mousePaint = false;
}
}
}
[New Code]
namespace Painter
{
public partial class Form1 : Form
{
Pen pen = new Pen(Color.Black, 1);
Point startingPoint = new Point(0, 0);
Point endPoint = new Point(0, 0);
bool mousePaint = false;
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = panel1.CreateGraphics();
if (mousePaint == true)
{
graphics.DrawLine(pen, startingPoint, endPoint);
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
startingPoint = e.Location;
if (e.Button == MouseButtons.Left)
{
mousePaint = true;
}
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if(mousePaint == true)
{
endPoint = e.Location;
}
startingPoint = endPoint;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
mousePaint = false;
}
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = panel1.CreateGraphics();
This is nonsense! Always and only use the e.Graphics object from the Paint param!!
Also: To trigger the Paint event do a panel1.Invalidate(); whenever your drawing data have changed!
Also: Make sure you understand just what your mousePaint flag is supposed to control: the mouse painting (i.e. adding new shapes to draw) or the regular painting (i. all shape previously drawn)!? Note that all drawing, current and previous needs to be done from the Paint event, whenever necessary i.e. over and over again!
To be able to do so: Collect all the shpes' data in a List<T>..
To Doublebuffer a Panel you need to subclass it. Your code turns on DoubleBuffering for the Form, which fine but won't help the Panel..
Instead simply use a PictureBox, which is control meant for drawing on!
A DoubleBuffered Panel subclass is as simple as this:
class DrawPanel : Panel
{
public DrawPanel()
{
DoubleBuffered = true;
}
}
Update: Instead you can also use a Label (with Autosize=false); it also has the DoubleBuffered property turned on out of the box and supports drawing better than Panels do.
The following code works fine but when resizing the application window the drawing dissappears.
This happens because resizing the application window invalidates portion of your panel which causes the portion to be redrawn.
Reason why your second approach is not working (the one labelled as [NEW CODE]) is because the Paint event is called only when relevant component is redrawn. You could partially solve this by forcing redraw of the panel in your MouseDown/MouseMove event handlers but you would still lose your previously painted stuff.
Possible solution is to create instance of Bitmap and paint there. Then just set this Bitmap as BackgroundImage of the panel. You can find more information on that here. Of course you would need to think about stuff like resizing and what should happen to the bitmap if application window gets shrunk or enlarged.
Here is some code that I quickly put together to get you started:
namespace WinForms_PaintTest
{
public partial class Form1 : Form
{
private Pen pen;
private Bitmap bitmap;
public Form1()
{
InitializeComponent();
this.pen = new Pen(Color.Black, 1);
this.bitmap = new Bitmap(this.panel1.Width, this.panel1.Height);
this.panel1.BackgroundImage = this.bitmap;
}
private void panel1_MouseMove(Object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
using (Graphics g = Graphics.FromImage(this.bitmap))
{
g.DrawRectangle(this.pen, e.Location.X, e.Location.Y, 1, 1);
}
this.panel1.Refresh();
}
}
private void Form1_FormClosed(Object sender, FormClosedEventArgs e)
{
this.pen.Dispose();
this.bitmap.Dispose();
}
}
}
Also regarding this:
this.DoubleBuffered = true;
I believe your intention was to prevent the flickering when relevant control is being redrawn? If that is case you need to set this property against the panel and not against the form itself. It is little bit tricky though because DoubleBuffered property of the panel is protected so you will need to either inherit from the panel or resort to reflection. You can find more information here .

Picturebox change location on mouseenter without white borders appearing

Hello I'm trying to do the effect that the button is pressed, so when mousenter moving 2px the picturebox, I'm using picturebox as button because It allows me to set transparent backgrounds.
I tried forcing the background to transparent in various events(paint,pevious change location,after change location),but without success.
I think that is caused for the re-drawing when changing an element, because the white part of the background that whas "hidden" by the picturebox appears.
Any idea how to solve that?
Thanks in advance
private void buttonX2_MouseLeave(object sender, EventArgs e)
{
((PictureBox) sender).Location = new Point(
((PictureBox) sender).Location.X, ((PictureBox) sender).Location.Y - 2);
}
private void buttonX2_MouseEnter(object sender, EventArgs e)
{
((PictureBox)sender).Location = new Point(
((PictureBox)sender).Location.X, ((PictureBox)sender).Location.Y + 2);
}
The problem seems to come from moving in or out too slowly. If you do that you will say enter from below, but the PB is moving up so you're out of it again, so it moves down and therefore you're in it again etc..The correct repainting of the Background can't keep up with these 'Jittering ButtBoxes'..
First, as Hans noted, make things less obtrusive: make the Form's BackColor dark, maybe even black!
Second to avoid the problem of jittering, move the Mouse Cursor itself a few pixels with the Pictureboxes, like this:
private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
PictureBox PB = (PictureBox)sender;
Point MP = Cursor.Position;
this.SuspendLayout();
PB.Location = new Point( PB.Location.X, PB.Location.Y - 2);
Cursor.Position = new Point(MP.X, MP.Y - 2);
this.ResumeLayout();
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
PictureBox PB = (PictureBox)sender;
Point MP = Cursor.Position;
this.SuspendLayout();
PB.Location = new Point( PB.Location.X, PB.Location.Y + 2);
Cursor.Position = new Point(MP.X, MP.Y + 2);
this.ResumeLayout();
}

2D Array of RectangleShapes

I am developing a very rudimentary drawing program: A 2D grid comprised of multiple RectangleShapes, around 20x30 pixels each, which when clicked change color based on user RGB input, which works just fine:
Color SelectedColor = new Color();
private void Pixel_1_1_Click(object sender, EventArgs e) // on Rectangle click
{
Pixel_1_1.FillColor = SelectedColor; // change to currently desired color.
}
Since the number of squares is rising dramatically, I'm looking for a way to arrange the "pixel" rectangles into a 2D array. (I really don't want to have to make a Pixel_Click method for every single Rectangle on the screen!) Hoping eventually to be able to call something like:
private void Pixel_[x]_[y]_Click(object sender, EventArgs e)
{
Pixel_[x]_[y].FillColor = SelectedColor;
}
My friends suggest the use of an anonymous delegate, but I don't understand how to fully use one to solve my problem.
What would be the best way to generate a 2D array of rectangles in a C# Windows Form? And once generated, how can I access them with a single method for variant values of x and y?
While you are probably correct in thinking of each rectangle as an object, it probably isn't correct to think of each rectangle as a windows control, especially since you have so many of them.
So try creating your own rectangle object:
public class MyRect {
public Color FillColor { get; set; }
public Rectangle Rectangle { get; set; }
public MyRect(Rectangle r, Color c) {
this.Rectangle = r;
this.FillColor = c;
}
}
Now you just need to keep a list of your objects and paint on a single Panel control (or PictureBox) all of your rectangles:
private List<MyRect> myRectangles = new List<MyRect>();
public Form1() {
InitializeComponent();
myRectangles.Add(new MyRect(new Rectangle(10, 10, 64, 16), Color.Blue));
myRectangles.Add(new MyRect(new Rectangle(20, 48, 16, 64), Color.Red));
}
private void panel1_Paint(object sender, PaintEventArgs e) {
foreach (MyRect mr in myRectangles) {
using (SolidBrush sb = new SolidBrush(mr.FillColor)) {
e.Graphics.FillRectangle(sb, mr.Rectangle);
}
}
}
To handle the "click" event of the rectangles, you just handle the MouseDown or MouseClick event of your container control and determine yourself which rectangle is being clicked on:
void panel1_MouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
foreach (MyRect mr in myRectangles) {
if (mr.Rectangle.Contains(e.Location)) {
ChangeColor(mr, Color.Green);
}
}
panel1.Invalidate();
}
}
private void ChangeColor(MyRect mr, Color newColor) {
mr.FillColor = newColor;
}
If you want to maintain the rectangles as components on screen then you can assign all of them the same click event, the click event will have a little dropdown to pick an existing event. To know which recantangle was clicked use the sender parameter ((Pixel)sender).FillColor = SelectedColor;
For ease I would recommend using something like a panel and drawing rectangles on it, That means you only have a single click event to deal with. So now your question becomes "How do I draw a grid of rectangles on a panel" and "How do I know which rectangle was clicked"
So for the first part you could use this not the very efficient way.
Create a class which stores the information about your pixels
class MyPixel
{
public Color PixelColour;
public Rectangle Bounds;
}
Keep a list of them in memory
List<MyPixels> MyGrid = new List<MyPixels>();
then in the onpaint event of the panel Draw the pixels on the panel
foreach(MyPixel Pixel in MyGrid)
{
using(Brush B = new SolidBrush(Pixel.PixelColor))
{
e.Graphics.DrawRectangle(B, Pixel.Bounds);
}
}
Now in the click event you'll need to know which pixel was clicked
foreach(MyPixel Pixel in MyGrid)
{
if (Pixel.Bounds.Contains(e.Location))
{
PixelClicked(Pixel);
}
}
I believe you're going about this the wrong way. What you want to do is to draw directly into a bitmap. Here is some code that uses a PictureBox to allow the user to draw into it.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Pen _pen;
private bool _mouseDown;
private int _startX;
private int _startY;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
_pen = new Pen(Color.Black);
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
_mouseDown = true;
_startX = e.X;
_startY = e.Y;
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
_mouseDown = false;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (_mouseDown)
{
using (var graphics = Graphics.FromImage(pictureBox1.Image))
{
graphics.DrawLine(_pen, _startX, _startY, e.X, e.Y);
_startX = e.X;
_startY = e.Y;
}
pictureBox1.Invalidate();
}
}
}
}
This is the normal method to write a painting app and is quite performant as well. You can also easily save, write new tools or manipulate images better in this way.

How to get the Coordinates of a Custom Image Cursor in c#?

Bitmap hh = (Bitmap)System.Drawing.Bitmap.FromFile("example.png");
Graphics.FromImage(hh);
IntPtr ptr = hh.GetHicon();
Cursor c = new Cursor(ptr);
this.Cursor = c;
I use this code to create a custom image cursor. I want to retrieve the coordinates of this custom image cursor when on a Click event. So that these coordinates can be used to draw the image of this cursor in a picture box when clicked on the image loaded in the picture box. I'm doing this in C#.
I tried another approach
public partial class Form1 : Form
{
private Bitmap _bmp = new Bitmap(250, 250);
public Form1()
{
InitializeComponent();
panel1.MouseDown += new MouseEventHandler(panel1_MouseDown);
panel1.Paint += new PaintEventHandler(panel1_Paint);
using (Graphics g = Graphics.FromImage(_bmp))
g.Clear(SystemColors.Window);
}
private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
Point mouseDownLocation = new Point(e.X, e.Y);
label1.Text = mouseDownLocation.X.ToString();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(_bmp, new Point(0, 0));
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
using (Graphics g = Graphics.FromImage(_bmp))
{
g.DrawString("Mouse Clicked Here!", panel1.Font, Brushes.Black, e.Location);
}
panel1.Invalidate();
}
private void button1_Click(object sender, EventArgs e)
{
panel1.Image.Save(#"C:\test.jpg", ImageFormat.Jpeg);
}
But when i try so save the image i get an Exception: Object reference not set to an instance of an object.
Please note that panel1 in the code above refers to a picture box
To get the coordinates of the mouse on a PictureBox you should not handle the OnClick event but the OnMouseDown, for example in this way:
private void pb_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
Point mouseDownLocation = new Point(e.X, e.Y);
}
now you have the mouseDownLocation which contains the coordinates you were looking for.
i know the way to get the coordinate of mouse you can code it like
Cursor.Position.X and Cursor.Position.Y to get the Coordinate under the mouse

Categories

Resources