After button click event I want the program to draw a rectangle inside a picturebox. I don't know how to do that. So far I made only a rectangle outside of picture box like this. Afterwards I want to implement a flood fill algorithm to fill the rectangle with a color. That's why I have to have those bitmaps there.
namespace howto_floodfill
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// The background image.
private Bitmap bm;
private Bitmap32 bm32;
// Make a rectangle
private void button1_Click(object sender, EventArgs e)
{
bm = new Bitmap(ClientSize.Width, ClientSize.Height);
using (Graphics gr = Graphics.FromImage(bm))
{
gr.Clear(Color.Silver);
gr.DrawRectangle(Pens.Black, 5, 5, 100, 60);
}
bm32 = new Bitmap32(bm);
this.BackgroundImage = bm;
}
}
}
You can set a Paint event handler for the PictureBox that will allow you to do drawing over the top of the PictureBox contents:
public partial class Form1 : Form
{
private bool _drawRectangle = false;
public Form1()
{
InitializeComponent();
pictureBox1.Paint += new PaintEventHandler(this.pictureBox1_Paint);
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (_drawRectangle) {
Graphics g = e.Graphics;
// use g to do your drawing
}
}
}
Just set _drawRectangle to true in your button click handler and call pictureBox1.Invalidate(). Doing your drawing in the Paint event handler guarantees that whenever the PictureBox is redrawn (say, because another window was over it), your rectangle gets drawn as well.
This will let you draw a rectangle over the PictureBox's contents. Rather than a flood fill algorithm, have you considered just using FillRectangle?
If you really want to do a flood fill, you'll have to work with an image as you're already doing, so you can read pixels from the image to know if a boundary has been reached. Then you could set the PictureBox's Image property with the resulting bitmap. (In this case, it wouldn't be necessary to do the graphics work in the Paint event handler, since the PictureBox will make sure its Image is drawn on every paint.)
You can use the control.CreateGraphics() method invoked from your picturebox.
namespace WindowsFormsApplication_Test
{
public partial class Form1 : Form
{
private Bitmap bm;
public Form1()
{
InitializeComponent();
bm = new Bitmap(pB.ClientRectangle.Width, pB.ClientRectangle.Height);
}
private void btn_Click(object sender, EventArgs e)
{
Graphics gF = pB.CreateGraphics();
gF.Clear(Color.Silver);
gF.DrawRectangle(Pens.Black, 5, 5, 100, 60);
}
private void button1_Click(object sender, EventArgs e)
{
Graphics gF = Graphics.FromImage(bm);
gF.Clear(Color.Silver);
gF.DrawRectangle(Pens.Black, 5, 5, 100, 60);
pB.Image = bm;
}
}
}
btn_click() is an example of getting the graphics context from the control and drawing directly.
Form prior to clicking...
Clicking the button will draw on the control directly - note that by default it gives you the clientRectangle portion of the control, which is nice...
Clicking on the button gives you this.
Now I resized the form.
Unfortunately, drawing on the form this way makes you responsible for redrawing your data any time the window is invalidated.
You can also just set the Image property of the form to be your private bitmap and then the framework handles redrawing for you. This is shown in the button1_Click() method.
You can still draw directly on the control if you wish, but you'll need to hook into the control events and redraw when the form does. For example, adding a flag as a private bool to the form class, overriding the OnPaint method, and adding code to your button event to swap the flag. Rather than duplicating the drawing code in the button event, you can just flip the flag and call this.Invalidate();
public partial class Form1 : Form
{
private Bitmap bm;
private bool bDrawn = false;
public Form1()
{
InitializeComponent();
bm = new Bitmap(pB.ClientRectangle.Width, pB.ClientRectangle.Height);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (bDrawn)
{
Graphics gF = pB.CreateGraphics();
gF.Clear(Color.Silver);
gF.DrawRectangle(Pens.Black, 5, 5, 100, 60);
}
}
private void btn_Click(object sender, EventArgs e)
{
//Graphics gF = pB.CreateGraphics();
//gF.Clear(Color.Silver);
///gF.DrawRectangle(Pens.Black, 5, 5, 100, 60);
bDrawn = true;
this.Invalidate();
}
Assign the created bitmap to the Image property of the picture box. Now you can draw whatever you want on the bitmap, and then manipulate it's data.
namespace howto_floodfill {
public partial class Form1 : Form {
private Bitmap bitmap;
public Form1() {
InitializeComponent();
this.bitmap = new Bitmap(100, 100);
this.pictureBox1.Image = this.bitmap;
}
// Make a rectangle
private void button1_Click(object sender, EventArgs e) {
if (this.bitmap != null) {
this.bitmap.Dispose();
}
this.bitmap = new Bitmap(ClientSize.Width, ClientSize.Height);
using (Graphics gr = Graphics.FromImage(bitmap)) {
gr.Clear(Color.Silver);
gr.DrawRectangle(Pens.Black, 5, 5, 100, 60);
}
this.pictureBox1.Image = this.bitmap;
}
}
}
Note that you may not need to re-create the bitmap each time if it has a fixed size.
Related
I'm interested in learning about C# GDI+ and have googled many tutorials. I'm attempting to create a simple windows form that has two textbox controls and a button. I simply want to put a length dimension in one textbox and a height dimension in the other, click the button and have the app draw the rectangle on the window using those two entered dimensions. To date, all I have been able to do is locate tutorials where the rectangle parameters are hardcoded into the Form_Load and Form_Paint. How would I take the user input from the textboxes and pass them to make the app refresh and draw the rectangles on the button click?
Please let me know if more info is needed.
Thanks in advance for your knowledge!
public partial class Form1 : Form
{
Bitmap drwBitmap;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Graphics graphicObj;
drwBitmap = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
graphicObj = Graphics.FromImage(drwBitmap);
graphicObj.Clear(Color.White);
Pen myPen = new Pen(System.Drawing.Color.Red, 3);
Rectangle rectObj;
rectObj = new Rectangle(10, 10, 100, 200);
graphicObj.DrawEllipse(myPen, rectObj);
graphicObj.Dispose();
}
private void Form1_Paint(object sender, PaintEventArgs e, Graphics graphicsObj)
{
Graphics graphicsObj1 = graphicsObj;
graphicsObj1.DrawImage(drwBitmap, 0, 0, drwBitmap.Width, drwBitmap.Height);
graphicsObj.Dispose();
}
The current approach is quite strange as it draws directly to the form. It's difficult to modify as a bitmap is created early on and then must somehow be changed. Furthermore, there is no need for a bitmap.
A better approach is to create a custom control:
public class EllipseControl : Control
{
private float m_ellipseWidth = 200;
private float m_ellipseHeight = 120;
public float EllipseWidth
{
get { return m_ellipseWidth; }
set
{
m_ellipseWidth = value;
Invalidate();
}
}
public float EllipseHeight
{
get { return m_ellipseHeight; }
set
{
m_ellipseHeight = value;
Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var graphics = e.Graphics;
using Pen pen = new Pen(System.Drawing.Color.Red, 3);
graphics.DrawEllipse(pen, 0, 0, EllipseWidth, EllipseHeight);
}
}
This control can then be placed on the form. It has two properties: EllipseWidth and EllipseHeight.
In the event handler for the button click, you can take the values from the text fields and set them on the ellipse control.
I have a WinForms application that interacts with a connection. If the connection is fine I want to show a green ("everything is fine") filled circle, if not I want to show a red filled circle.
I found no circle element in the toolbox so I think I have to draw it on my own.
I created a picture box called picBoxClientState and started with this code
public partial class FrmMain : Form
{
public void CheckSignedInState()
{
// some other code
DrawClientStateIcon(client.IsSignedIn);
}
private void DrawClientStateIcon(bool isSignedIn)
{
Point rectangleLocation = picBoxClientState.Location;
Size rectangleSize = picBoxClientState.Size;
Rectangle rectangle = new Rectangle(rectangleLocation, rectangleSize);
Color iconColor = isSignedIn ? Color.Green : Color.Red;
SolidBrush iconBrush = new SolidBrush(iconColor);
Graphics graphics = picBoxClientState.CreateGraphics();
graphics.FillEllipse(iconBrush, rectangle);
}
}
How can I draw on this picturebox whenever I call CheckSignedInState() ?
Maybe there is a better way instead of drawing? (I don't want to toggle two images because there might be more states to draw)
A simple example using a Label control to draw an ellipse.
You can use any control that has a Paint event to draw shapes.
It could also be a Panel, a PictureBox, a Button...
A bool variable (clientIsSignedIn) declared at Class scope is used to keep track of the current status, as reported by your client.IsSignedIn value.
When the status changes, update clientIsSignedIn and Invalidate() the Control that provides the visual aid.
bool clientIsSignedIn = false;
public void CheckSignedInState()
{
// some other code
clientIsSignedIn = client.IsSignedIn;
lblVisualStatus.Invalidate();
}
private void lblVisualStatus_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.FillEllipse((clientIsSignedIn) ? Brushes.Green : Brushes.Red, ((Control)sender).ClientRectangle);
}
I don't think picture box is necessary. You can try something like this:
private void button1_Click(object sender, EventArgs e)
{
System.Drawing.SolidBrush myBrush = new
System.Drawing.SolidBrush(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.FillEllipse(myBrush, new Rectangle(200, 200, 30, 30));
myBrush.Dispose();
formGraphics.Dispose();
}
If you need to draw on picturebox be sure to call picturebox.Invalidate();
your code works, it did seem to draw a bit off center though but also the fact that you weren't disposing of the object could potentially cause issues too. Try using the code below as your DrawClientStateIcon method
Edit: full code example below. I added a button to toggle the state of the client and this works for me.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public class Client
{
public bool IsSignedIn { get; set; }
}
Client client = new Client()
{
IsSignedIn = false
};
public Form1()
{
InitializeComponent();
}
public void CheckSignedInState()
{
// some other code
DrawClientStateIcon(client.IsSignedIn);
}
private void DrawClientStateIcon(bool isSignedIn)
{
Point rectangleLocation = picBoxClientState.Location;
Size rectangleSize = picBoxClientState.Size;
Rectangle rectangle = new Rectangle(rectangleLocation, new Size(rectangleSize.Width / 2, rectangleSize.Height / 2));
Color iconColor = isSignedIn ? Color.Green : Color.Red;
using (SolidBrush iconBrush = new SolidBrush(iconColor))
{
using (Graphics graphics = picBoxClientState.CreateGraphics())
{
graphics.FillEllipse(iconBrush, rectangle);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
client.IsSignedIn = !client.IsSignedIn;
CheckSignedInState();
}
}
}
You need to call it in Form Shown event.
private void FrmGraphics_Shown(object sender, EventArgs e)
{
DrawClientStateIcon(true);
}
private void DrawClientStateIcon(bool isSignedIn)
{
Point rectangleLocation = picBoxClientState.Location;
Size rectangleSize = picBoxClientState.Size;
Rectangle rectangle = new Rectangle(rectangleLocation, rectangleSize);
Color iconColor = isSignedIn ? Color.Green : Color.Red;
SolidBrush iconBrush = new SolidBrush(iconColor);
Graphics graphics = base.CreateGraphics();
graphics.FillEllipse(iconBrush, rectangle);
}
I made an user control and I draw a rectangle directly in the window, like this (this is a simplified version):
private int rec_len = 200;
private void Draw_()
{
Pen pn = new Pen( Color.Black, WIDTH_LINE );
Graphics graph = this.CreateGraphics();
graph.Clear( Color.Transparent );
this.Refresh();
graph.DrawRectangle( pn, 20, 10, rec_len, 40 );
this.Refresh();
graph.Dispose();
}
public void button_Build_Click( object sender, EventArgs e )
{ rec_len += 10; Draw_(); }
The strange thing is that the second refresh actually poses a problem: if I comment it out, the rectangle is visible, if I let it in the code, the rectangle is not visible. In the real code I have to draw more than a rectangle and I want the refresh at the end, otherwise the background is visible between the moment I erase old drawing and the moment the new one is ready.
The surface of a control is not stored: When you paint on a control, the drawing is not saved and need to be redrawn each time the control is repainted (After a refresh for example). To create a persistante graphic, you can create a bitmap, draw on the bitmap and assign this bitmap to the BackgroundImage property.
Bitmap bmp = new Bitmap(WIDTH, HEIGHT);
void Initialize()
{
this.BackgroundImage = bmp;
}
private int rec_len = 200;
private void Draw_()
{
Pen pn = new Pen(Color.Black, WIDTH_LINE);
using (Graphics graph = Graphics.FromImage(bmp))
{
graph.Clear(Color.Transparent);
this.Refresh();
graph.DrawRectangle(pn, 20, 10, rec_len, 40);
this.Refresh();
}
}
public void button_Build_Click(object sender, EventArgs e) { rec_len += 10; Draw_(); }
Given the following code example from MSDN:
private void GetPixel_Example(PaintEventArgs e)
{
// Create a Bitmap object from an image file.
Bitmap myBitmap = new Bitmap(#"C:\Users\tanyalebershtein\Desktop\Sample Pictures\Tulips.jpg");
// Get the color of a pixel within myBitmap.
Color pixelColor = myBitmap.GetPixel(50, 50);
// Fill a rectangle with pixelColor.
SolidBrush pixelBrush = new SolidBrush(pixelColor);
e.Graphics.FillRectangle(pixelBrush, 0, 0, 100, 100);
}
How can one call the Paint function?
from the paint event something like this
private PictureBox pictureBox1 = new PictureBox();
pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
GetPixel_Example(e) ;
}
You can call this method from a PaintEvent of a form e.g.
public class Form1 : Form
{
public Form1()
{
this.Paint += new PaintEventHandler(Form1_Paint);
}
//....
private void Form1_Paint(object sender, PaintEventArgs e)
{
GetPixel_Example(e);
}
private void GetPixel_Example(PaintEventArgs e)
{
// Create a Bitmap object from an image file.
Bitmap myBitmap = new Bitmap(#"C:\Users\tanyalebershtein\Desktop\Sample Pictures\Tulips.jpg");
// Get the color of a pixel within myBitmap.
Color pixelColor = myBitmap.GetPixel(50, 50);
// Fill a rectangle with pixelColor.
SolidBrush pixelBrush = new SolidBrush(pixelColor);
e.Graphics.FillRectangle(pixelBrush, 0, 0, 100, 100);
}
}
Loads the image
Get the color of the pixel at x=50,y=50
Draw a filled rectangle with that color at 0,0 with a size of 100,100
on the Graphics-Object of the form
You should't call the Paint method yourself. The Paint method will be called by the .NET framework whenever your component needs to be painted. This typically happens when the window is moved, minimized, etc.
If you want to tell the .NET framework to repaint your component, call Refresh() on either the component or one of its parents.
class OriginalImage: Form
{
private Image image;
private PictureBox pb;
public OriginalImage()
{
pb = new PictureBox {SizeMode = PictureBoxSizeMode.CenterImage};
pb.SizeMode = PictureBoxSizeMode.StretchImage;
Controls.Add(pb);
image = Image.FromFile(#"Image/original.jpg");
this.Width = image.Width;
this.Height = image.Height;
this.Text = "Original image";
this.Paint += new PaintEventHandler(Drawer);
}
public virtual void Drawer(object source, PaintEventArgs e)
{
Graphics g = pb.CreateGraphics();
g.DrawImage(image,0,0);
}
I call this create object OriginalImage in other form on button click, but image is not draw? Where is problem?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var oi = new OriginalImage();
oi.Show();
}
}
You're creating a PictureBox and adding it to your controls, but you never actually use it (you're drawing the image manually in the Paint event). Why? This control is likely obscuring the drawing area of the form, as any controls go on top of whatever you draw in the Paint event.
In addition, you're getting the Graphics object by calling CreateGraphics on the PictureBox rather than the Form itself. This is wrong, as the PictureBox's Paint event will fire after this code, erasing whatever you draw.
I would recommend changing your OriginalForm code to the following:
class OriginalImage: Form
{
private Image image;
private PictureBox pb;
public OriginalImage()
{
pb = new PictureBox();
pb.SizeMode = PictureBoxSizeMode.StretchImage;
pb.Dock = DockStyle.Fill; // this will make the PictureBox occupy the
// whole form
Controls.Add(pb);
image = Image.FromFile(#"Image/original.jpg");
this.ClientSize = new Size(image.Width, image.Height); // this allows you to
// size the form while
// accounting for the
// border
this.Text = "Original image";
pb.Image = image; // use this instead of drawing it yourself.
}
}