I have a function that will draw a image to a form.
private void DrawImage()
{
OpenFileDialog openfiledialog = new OpenFileDialog();
if (openfiledialog.ShowDialog() == DialogResult.OK)
{
Bitmap image = (Bitmap)Image.FromFile(openfiledialog.FileName, true);
TextureBrush texturebrush = new TextureBrush(image);
texturebrush.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile;
Graphics formGraphics = this.CreateGraphics();
formGraphics.FillRectangle(texturebrush, new RectangleF(90.0F, 110.0F, 00, 300));
formGraphics.Dispose();
}
}
But i will not draw any image and same code works if i write in button click event.
private void button1_Click(object sender, EventArgs e)
{
//Same code as written in DrawImage()
}
The problem I think is it needs "EventArgs e" in it. I read some where in msdn but not sure.No idea what is the role of EventArgs in drawing image on form.
Is there any way that I can achieve this functionality.
Consider these tips to solve the problem:
If you use this.CreateGraphics
for drawing on your form, then your drawing will disappear if the form refershes, for example if you minimize and restore it. You should put drawing logic in Paint
event.
When refactoring your method, you should pass a parameter of Graphics
type to your method and use it for drawing. Also you should not dispose passed parameter. You should pass e.Graphics
in Paint
event to your method.
In your method you should dispose your brush. Put it in a using
block.
When refactoring your method, you should move the part of code which shows a dialog to out of your method. You should call it just when you need not in Paint
event handler.
Preferably Don't use Image.FromFile
to load image, it locks the file until the images disposes. Instead use Image.FromStream
.
You are using a rectangle with 0
as Width
. So if you draw even using current method, you will not see any result because of width of rectangle.
Code
Bitmap image;
private void DrawImage(Bitmap image, Graphics g, Rectangle r)
{
using (var brush = new TextureBrush(image))
{
brush.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile;
g.FillRectangle(brush, r);
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
using (var s = new System.IO.FileStream(dialog.FileName, System.IO.FileMode.Open))
image = new Bitmap(Image.FromStream(s));
this.Invalidate();
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (image != null)
this.DrawImage(image, e.Graphics, new RectangleF(10, 10, 200, 200));
}