I've been reading stackoverflow for a while now just to learn, and I've come across a situation where I can finally ask a question. I'm making a Simon Says type memory game, where I flash shapes at the user, and the user has to click a button in the same order the shapes were shown to them. I want to draw the shape that I'm drawing on the screen within the button that they are clicking because it's much easier to remember and compare shapes to shapes rather than shapes to a button that says the shapes name.
Hopefully my question is clear, and thanks for taking a look!
Yes, you can set the Image property of Button. Alternatively, you can draw non-rectangular buttons, that is, buttons of any shape. The following code demonstrates both techniques:
using System;
using System.Drawing;
using System.Windows.Forms;
class ShapeButton : Button {
public Action<PaintEventArgs> DoPaint { get; set; }
protected override void OnPaint(PaintEventArgs e) {
if (DoPaint != null) { DoPaint(e); }
}
}
static class Program {
static void Main() {
// Ellipse button
ShapeButton ellipseButton = new ShapeButton();
ellipseButton.Location = new Point(10, 10);
ellipseButton.Size = new Size(80, 80);
ellipseButton.DoPaint = delegate(PaintEventArgs e) {
Graphics graphics = e.Graphics;
SolidBrush brush1 = new SolidBrush(SystemColors.ButtonFace);
graphics.FillRectangle(brush1, 0, 0, ellipseButton.Width, ellipseButton.Height);
SolidBrush brush2 = new SolidBrush(Color.Red);
graphics.FillEllipse(brush2, 0, 0, ellipseButton.Width, ellipseButton.Height);
};
ellipseButton.Click += delegate(object sender, EventArgs e) {
MessageBox.Show("Ellipse!");
};
// Triangle button
ShapeButton triangleButton = new ShapeButton();
triangleButton.Location = new Point(100, 10);
triangleButton.Size = new Size(80, 80);
triangleButton.DoPaint = delegate(PaintEventArgs e) {
Graphics graphics = e.Graphics;
SolidBrush brush1 = new SolidBrush(SystemColors.ButtonFace);
graphics.FillRectangle(brush1, 0, 0, triangleButton.Width, triangleButton.Height);
SolidBrush brush2 = new SolidBrush(Color.Green);
Point[] points = {
new Point(triangleButton.Width / 2, 0),
new Point(0, triangleButton.Height),
new Point(triangleButton.Width, triangleButton.Height)
};
graphics.FillPolygon(brush2, points);
};
triangleButton.Click += delegate(object sender, EventArgs e) {
MessageBox.Show("Triangle!");
};
// Star button (using image)
Button starButton = new Button();
starButton.Location = new Point(190, 10);
starButton.Size = new Size(80, 80);
starButton.Image = new Bitmap("Star.png");
starButton.Click += delegate(object sender, EventArgs e) {
MessageBox.Show("Star!");
};
// The form
Form form = new Form();
form.Text = "Shape Button Test";
form.ClientSize = new Size(280, 100);
form.Controls.Add(ellipseButton);
form.Controls.Add(triangleButton);
form.Controls.Add(starButton);
form.ShowDialog();
}
}
Result (after clicking on the triangle button):
In winforms to change the button's image at runtime you can use something like this:
button1.Image = new Bitmap(Image.FromFile(#"Pictures\Koala.jpg"));
It should be added to event handler. For example if you want to show the image when the button is clicked you subscribe to Click event of the button and add the code into the handler method:
private void button1_Click(object sender, EventArgs e)
{
button1.Image = new Bitmap(Image.FromFile(#"Pictures\Koala.jpg"));
}
In my example,
I have a pictureBox to show, two buttons, one to control, one to be drawn.
//odd display, even draw
int count = 0;
Image storePicture;
//whenever the background image changed,store it
private void pictureBoxShow_BackgroundImageChanged(object sender, EventArgs e)
{
//you can stored to a Image array if you have series pictures to show
storePicture = pictureBoxShow.BackgroundImage;
}
private void buttonControl_Click(object sender, EventArgs e)
{
count++;
//odd show picture, even draw picture on button
if (count % 2 == 1)
pictureBoxShow.BackgroundImage = new Bitmap("shapes.JPG");
else
{
//in case you want to clear text on the button
buttonDrawn.Text = null;
//recreate the picture so that it fit the button size
buttonDrawn.Image = new Bitmap(storePicture, new Size(buttonDrawn.Width, buttonDrawn.Height));
}
}
Please remember to attach the handlers to corresponding events. ^^
Why not using PictureBox instead of Buttons.
you have just to add your task to its event/OnClick
Of course you can load any Image to any PictureBox in runtime
The code above is great, however you can click outside the circle within a square containing the circle and get the click event.
If you want to capture the click only if the user clicks inside the shape you have to set the region property with something like this
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(0, 0, 100, 100);
Button1.Region = new Region(gp);
}
}
Related
I'm trying to dynamically create a picture box by clicking a button. However, I want to have the code that creates the picture box (and also creates some graphs in that picture box) in a dll file. When i move the code from my main form to a method in a dll file and then call that method in the button click event in my main form nothig happens.
I've been searching high and low for an answer but with little success. The most relevant thing that I found is here. However, I struggle to create an instance of my main form to pass to the method in the dll...The answer might be bluntly obvious but I am very new to c#... Also, I am using Visual Studio 2013 if that is of any relevance.
Here is the method in the dll:
namespace DrillGraph
{
public class DrillGraph : UserControl
{
public DrillGraph() { }
public void CreateGraph()
{
PictureBox pb = new PictureBox();
pb.Dock = DockStyle.Fill;
pb.BackColor = Color.Bisque;
pb.Name = "pb";
pb.Size = new Size(50, 50);
pb.Location = new Point(20, 20);
Graphics g = pb.CreateGraphics();
g.DrawEllipse(new Pen(Color.Red), 0, 0, 50, 50);
this.Controls.Add(pb);
}
}
}
And this is what i have in my main form:
using DrillGraph;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
DrillGraph.DrillGraph dg = new DrillGraph.DrillGraph();
private void button1_Click(object sender, EventArgs e)
{
dg.CreateGraph();
}
}
}
Adding where? you should provide the reference in your dll.
public void CreateGraph(Panel pnl)
{
PictureBox pb = new PictureBox();
pb.Dock = DockStyle.Fill;
pb.BackColor = Color.Bisque;
pb.Name = "pb";
pb.Size = new Size(50, 50);
pb.Location = new Point(20, 20);
Graphics g = pb.CreateGraphics();
g.DrawEllipse(new Pen(Color.Red), 0, 0, 50, 50);
pnl.Controls.Add(pb);
}
Then call below code
dg.CreateGraph(YourPanelName From Form);
How to draw image on tabPage overlapping buttons
Black circles(DrawImage on tabPage8_Paint) should be above the buttons:
http://rghost.ru/6sVBl8mkh/image.png
It must be so:
http://rghost.ru/6BgDM77pq/image.png
My code
public SibModem() {
InitializeComponent();
tabPage8.Paint += new PaintEventHandler(tabPage8_Paint);
gettime();
this.SizeChanged += new EventHandler(this.SibModem_Resize);
}
protected void tabPage8_Paint(object sender, PaintEventArgs e) {
GraphicsUnit units = GraphicsUnit.Pixel;
base.OnPaint(e);
Graphics g = e.Graphics;
g.DrawImage(bg, 0, 0);
Rectangle srcRect = new Rectangle(offsetant, 0, w, h);
g.DrawImage(anten, x, y, srcRect, units);
Rectangle ussdwaitRect = new Rectangle(offsetussd, 0, 64, 64);
g.DrawImage(ussdwait, usx, usy, ussdwaitRect, units);
}
You can't draw above nested controls, so you need to draw parts of the image onto those Buttons.
So combine drawing onto the tabpage and drawing onto the buttons you need to adorn!
Here is a simple example using only one image:
A few class level variables:
Point iLoc = Point.Empty;
Image img = null;
List<Button> overlaidButtons = new List<Button>();
Prepare the image, its position and a list of possibly overlaid buttons:
public Form1()
{
InitializeComponent();
string imgN = #"d:\scrape\gears\gear_12x4hand.png";
img = Image.FromFile(imgN);
iLoc = new Point(100, 100);
overlaidButtons.AddRange(new []{button10,button11,button12,button13 });
// each button calls the same paint event
foreach (Button btn in overlaidButtons) btn.Paint += btn_Paint;
}
The common Paint event. We calculate the relative position of the image..
void btn_Paint(object sender, PaintEventArgs e)
{
Button btn = sender as Button;
e.Graphics.DrawImage(img, new Point(iLoc.X - btn.Left, iLoc.Y - btn.Top));
}
Note that if the Buttons are nested deeper you need to adapt the calculation to include all levels of nesting!
The TabPage Paint event:
private void tabPage5_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(img, iLoc);
}
Try BringToFront method, it brings the control to the front of the z-order.
See this reference on MSDN: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.bringtofront(v=vs.110).aspx
I have a Panel called panel1 and I am trying to draw a line on my panel1 using this code:
var g = panel1.CreateGraphics();
var p = new Pen(Color.Black, 3);
var point1 = new Point(234,118);
var point2 = new Point(293,228);
g.DrawLine(p, point1, point2);
But nothing is showing up. Any ideas? This is in a windows form.
Handle the Panel's Paint event and put it in there. What's happening is that it's being drawn once in the constructor but then being drawn over in the Paint event everytime it's called.
private void panel1_Paint(object sender, PaintEventArgs e)
{
base.OnPaint(e);
using(Graphics g = e.Graphics)
{
var p = new Pen(Color.Black, 3);
var point1 = new Point(234,118);
var point2 = new Point(293,228);
g.DrawLine(p, point1, point2);
}
}
Put it in some event after the form has been created and shown on the screen and it should work fine.
It's best to put it in the Paint event, as keyboardP stated, but it will not show up if called before the form is shown on the screen.
To test this you can add a button and add the code to the click event:
private void button1_Click(object sender, EventArgs e)
{
using (Graphics g = panel1.CreateGraphics())
{
g.DrawLine(new Pen(Color.Back, 3), new Point(234,118), new Point(293,228));
}
}
To see your drawing - you can simply make a button with a Click Event and draw when the button is clicked. For example:
private void btnDraw_Click(object sender, EventArgs e)
{
Graphics dc = drawingArea.CreateGraphics();
Pen BlackPen = new Pen(Color.Black, 2);
dc.DrawLine(BlackPen, 0, 0, 200, 200);
BlackPen.Dispose();
dc.Dispose();
}
Oh, and by the way "drawingArea" is the (Name) of either a PictureBox or Panel you have added to your form (to draw in it).
If you follow the other answers and still your drawings are not showing up try removing all controls from the control that is being drawn to. The other controls may be covering whatever you are trying to draw.
private void button2_Click(object sender, EventArgs e)
{
panel1.Paint += new PaintEventHandler(
(object sender1, PaintEventArgs e1) => {
var p = new Pen(Color.Black, 3);
var point1 = new Point(234, 118);
var point2 = new Point(293, 228);
e1.Graphics.DrawLine(p, point1, point2);
}
);
panel1.Invalidate();
}
I have created a function that loops a folder and retrieves each image file and draw a picturebox on the form.
Here is the function :
private void Create_Controls(string Img_path)
{
PictureBox p = new PictureBox();
p.Size = new Size(138, 100);
p.Location = new Point(6, 6);
p.BackgroundImage = Image.FromFile(Img_path);
p.BackgroundImageLayout = ImageLayout.Stretch;
this.Controls.Add(p);
}
So what i need to do is : whenever i click on any picturebox on the form , a message popup with the image file path.
So i thought about adding a custom event :
p.Click += delegate { Pop_Up(); };
AND
private void Pop_Up()
{
/* POP UP MESSAGE WITH Picturebox image file path*/
}
You need to use the property ImageLocation of the PictureBox . The property gets or sets the path or URL for the image to display in the PictureBox.
Just do the following:
p.Click += new EventHandler(Pop_Up);
...
private void Pop_Up(object sender, EventArgs e)
{
var pb = sender as PictureBox;
if(pb != null)
MessageBox.Show(pb.ImageLocation);
}
You could use Tag property for this.
something like this .
private void Create_Controls(string Img_path)
{
PictureBox p = new PictureBox();
p.Size = new Size(138, 100);
p.Location = new Point(6, 6);
p.Tag = Img_path;
p.BackgroundImage = Image.FromFile(Img_path);
p.BackgroundImageLayout = ImageLayout.Stretch;
this.Controls.Add(p);
}
private void Pop_Up()
{
MessageBox.Show(p.Tag);
}
For more on this Go here.
Then along with what HatSoft says, change your Pop_up() method like:
private void Pop_Up(object sender, EventArgs e)
{
MessageBox.Show(((PictureBox)sender).ImageLocation);
}
But maybe a bit more elegant and checking if it is indeed a PictureBox etc.
I want to draw a editable TextBox on top of picture box and the user is allowed to enter text into this box.After entering text the text box should disappear and the text entered should be painted to the picture in the picture box.Please help me on this,I'am doing this in c#.
Bitmap myBitmap = new Bitmap("C:\\myImage.jpg");
Graphics g = Graphics.FromImage(myBitmap);
g.DrawString("My\nText", new Font("Tahoma", 20), Brushes.White, new PointF(0, 0));
Im stuck with this
I think you are confusing "drawing" with the "editable" part.
It sounds like you just want to use a TextBox. A "basic" demonstration:
private Bitmap bmp = new Bitmap(256, 256);
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Image = bmp;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
TextBox txt = new TextBox();
txt.Location = e.Location;
txt.Width = 120;
txt.Leave += new EventHandler(txt_Leave);
pictureBox1.Controls.Add(txt);
}
void txt_Leave(object sender, EventArgs e)
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawString(((TextBox)sender).Text, ((TextBox)sender).Font, Brushes.Black, ((TextBox)sender).Location);
}
((TextBox)sender).Leave -= new EventHandler(txt_Leave);
pictureBox1.Controls.Remove((TextBox)sender);
((TextBox)sender).Dispose();
pictureBox1.Invalidate();
}
Sound like a TextBox control of MSPaint program, is it right?
Try this approach: http://bytes.com/topic/c-sharp/answers/230866-how-insert-text-bitmap-image-using-c
Hope this help.
But in your code the only way to actually draw the text from textBox is to change focus on something else (e.g. by Tab key).
https://stackoverflow.com/a/7350238/2359840