C# Winforms - Check when moveable drawn image is over a label - c#

I have an image drawn on the form which can be moved by the arrow keys.
It's created in the paint method as such:
int _x = 500; // initial x co-ordinate
int _y = 600; // initial y co-ordinate
private void testForm_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(new Bitmap("carImage.png"), _x, _y, 150, 100);
}
I also have some labels on the form, and the aim is that when the image is moved over a label and space is pressed, the text on the label changes.
What I'm confused about is how to check if the image is at the right location when space is pressed, i.e. if it is on top of the label.
I tried a few different ways, including this:
case Keys.Space:
foreach (Control control in this.Controls)
{
if (control is Label)
{
for (int i = _x; i < _x + 150; i++)
{
for (int j = _y; j > _y - 100; j--)
{
// If carImage within bounds of control
if (control.Bounds.Contains(i, j))
control.Text = "newText";
}
}
}
}
But this doesn't seem to work in my code, and I think even if it did it may be slow, as it has to iterate through so many times.
I also tried using
control.Bounds.IntersectsWith(carImage.Bounds ...)
but I'm not sure what object type the image should be in order to use it as the method argument.
I tried making the image a type Bitmap, but it wouldn't have a .Bounds property (there is only GetBounds() ). I think I could use carImage.Height etc., but I'm still not sure how I would check whether they overlap using this.
So, two questions:
Is there another way to check if any of the image co-ordinates overlap with the label bounds, and, if not,
What type to set the image as so that it can be called in control.Bounds.IntersectsWith(), and how exactly to get that method to work with the image bounds (i.e. what should be inside the parentheses).
Any help is much appreciated!

Try this way:
Bitmap _image = new Bitmap("carImage.png");
int _x = 500; // initial x co-ordinate
int _y = 600; // initial y co-ordinate
private void testForm_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(_image, _x, _y);
}
private void CheckIntersect()
{
Rectangle imageBounds = new Rectangle(_x, _y, _image.Width, _image.Height);
if (label1.Bounds.IntersectsWith(imageBounds))
control.Text = "newText";
}

Related

Custom control using ScrollableControl with fixed position text

I'm building custom user control that will be used to display tiles map, as base class I've chosen ScrollableControl, because I want to have scrollbars in my control.
I've successfully created paint logic that is responsible for painting only needed elements.
Now I'm trying to add static text that will be always visible in same place (in my case white box with red text in top left corner):
This isn't clearly visible on above gif, but that white box blinks and jumps a bit when I scroll using mouse or scrollbars.
My question is how should I change my code to have scrollable content and fixed position content on top of that scrollable content?
Is ScrollableControl good choice as base class?
Below is my code:
class TestControl : ScrollableControl
{
private int _tileWidth = 40;
private int _tileHeight = 40;
private int _tilesX = 20;
private int _tilesY = 20;
public TestControl()
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.Opaque, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
UpdateStyles();
ResizeRedraw = true;
AutoScrollMinSize = new Size(_tilesX * _tileWidth, _tilesY * _tileHeight);
Scroll += (sender, args) => { Invalidate(); };
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.FillRectangle(new SolidBrush(BackColor), ClientRectangle);
e.Graphics.TranslateTransform(AutoScrollPosition.X, AutoScrollPosition.Y);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
var offsetX = (AutoScrollPosition.X * -1) / _tileWidth;
var offsetY = (AutoScrollPosition.Y * -1) / _tileHeight;
var visibleX = Width / _tileWidth + 2;
var visibleY = Height / _tileHeight + 2;
var x = Math.Min(visibleX + offsetX, _tilesX);
var y = Math.Min(visibleY + offsetY, _tilesY);
for (var i = offsetX; i < x; i++)
{
for (var j = offsetY; j < y; j++)
{
e.Graphics.FillRectangle(Brushes.Beige, new Rectangle(i*_tileWidth, j*_tileHeight, _tileWidth, _tileHeight));
e.Graphics.DrawString(string.Format("{0}:{1}", i, j), Font, Brushes.Black, new Rectangle(i * _tileWidth, j * _tileHeight, _tileWidth, _tileHeight));
}
}
using (var p = new Pen(Color.Black))
{
for (var i = offsetX + 1; i < x; i++)
{
e.Graphics.DrawLine(p, i*_tileWidth, 0, i*_tileWidth, y*_tileHeight);
}
for (var i = offsetY + 1; i < y; i++)
{
e.Graphics.DrawLine(p, 0, i*_tileHeight, x*_tileWidth, i*_tileHeight);
}
}
e.Graphics.FillRectangle(Brushes.White, AutoScrollPosition.X * -1, AutoScrollPosition.Y * -1, 35, 14);
e.Graphics.DrawString("TEST", DefaultFont, new SolidBrush(Color.Red), AutoScrollPosition.X * -1, AutoScrollPosition.Y * -1);
}
}
EDIT:
I've searched a bit and found UserControl that has similar functionality - https://www.codeproject.com/Articles/16009/A-Much-Easier-to-Use-ListView and after reading a bit more on control's author blog http://objectlistview.sourceforge.net/cs/blog1.html#blog-overlays I found out that he is using Transparent Form that is positioned on top of control.
I really would like to avoid that, but still have overlay on top of my control.
You are doing battle with a Windows system option named "Show window content while dragging". Always turned on by default, this web page shows how to turn it off.
Solves the problem, but it is not something you can rely on since it affects all scrollable window in all apps. Demanding that the user turns it off for you is unrealistic, users like this option so they'll just ignore you. That they did not provide an option to turn it off for a specific window was a pretty major oversight. It is an okay solution in a kiosk app.
Briefly, the way the option works is that Windows itself scrolls the window content with the ScrollWindowEx() winapi function. Using a bitblt of the window content to move pixels and only generating a paint request for the part of the window that was revealed by the scroll. Usually only a few lines of pixels, so completes very fast. Problem is, that bitblt moves your fixed pixels as well. The repaint moves them back. Pretty noticeable, the human eye is very sensitive to motion like that, helped avoid being lion lunch for the past million years.
You'll have to take the sting out of ScrollWindowsEx(), preventing it from moving pixels even though you can't stop it from being called. That takes a heavy sledgehammer, LockWindowUpdate(). You'll find code in this post.
using System.Runtime.InteropServices;
...
protected override void OnScroll(ScrollEventArgs e) {
if (e.Type == ScrollEventType.First) {
LockWindowUpdate(this.Handle);
}
else {
LockWindowUpdate(IntPtr.Zero);
this.Update();
if (e.Type != ScrollEventType.Last) LockWindowUpdate(this.Handle);
}
}
[DllImport("user32.dll", SetLastError = true)]
private static extern bool LockWindowUpdate(IntPtr hWnd);
Not that pretty, using a separate Label control ought to start sounding attractive.
can you just add a label to that control(on top), in other words - cant you use it as panel?

Why am I having trouble writing a pixel to a picturebox in Visual C#?

I am writing an emulator program, and the virtual display is supposed to be able to take in 3 bytes of color data and display the correct color pixel, similar to how a real screen works. But when I set up some scroll bars to test the generation of pixels nothing happens. Here is my code and a screenshot of the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TSC_Multi_System_Emulator
{
public partial class Form1 : Form
{
private PictureBox Display = new PictureBox();
string #emulationfolderpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Bitmap screen = new Bitmap(#Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\Resource_Folder\" + #"FirstFrame.bmp");
int x = 0;
int y = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e) {
// Dock the PictureBox to the form and set its background to black.
Display.BackColor = Color.Black;
// Connect the Paint event of the PictureBox to the event handler method.
// Add the PictureBox control to the Form.
this.Controls.Add(Display);
}
public void DigitalGraphicsDisplay(int red, int green, int blue) {
Graphics g = Display.CreateGraphics();
screen.SetPixel(x, y, Color.FromArgb(red, green, blue));
g.DrawImage(screen, 0, 0, screen.Width, screen.Height);
g.Save();
if (x < screen.Width)
{
x = x + 1;
}
else if (x == screen.Width)
{
x = 0;
if (y < screen.Height)
{
y = y + 1;
}
else if (y == screen.Height)
{
y = 0;
}
}
}
private void button1_Click(object sender, EventArgs e){
int rchannel = redControl.Value;
int gchannel = greenControl.Value;
int bchannel = blueControl.Value;
DigitalGraphicsDisplay(rchannel, gchannel, bchannel);
}
}
}
UPDATE:
The code is now working somewhat, but I can't test the code using just a test button. I had to use the exact code given to me in the first answer, which only displayed a gradient, I wonder what I am doing wrong... :(
public partial class Form1 : Form
{
string #emulationfolderpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Bitmap screen = new Bitmap(#Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\Resource_Folder\" + #"FirstFrame.bmp");
int x = 0;
int y = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e) {
// Dock the PictureBox to the form and set its background to black.
Display.BackColor = Color.Black;
// Connect the Paint event of the PictureBox to the event handler method.
// Add the PictureBox control to the Form.
this.Controls.Add(Display);
}
public void DigitalGraphicsDisplay(int red, int green, int blue)
{
if (Display.Image == null)
{
Bitmap NewBMP = new Bitmap(Display.ClientRectangle.Width, Display.ClientRectangle.Height);
using (Graphics g = Graphics.FromImage(NewBMP))
{
g.Clear(Color.White);
}
Display.Image = NewBMP;
}
(Display.Image as Bitmap).SetPixel(x, y, Color.FromArgb(red, green, blue));
Display.Invalidate();
x++;
if (x >= Display.Image.Width)
{
x = 0;
y++;
if (y >= Display.Image.Height)
{
y = 0;
}
}
}
private void button1_Click(object sender, EventArgs e){
Boolean a = false;
int b = 0;
do
{
DigitalGraphicsDisplay(51, 153, 102);
if (b == 10000)
{
a = true;
}
b = b + 1;
} while (a);
}
}
}
All I am getting is a white picturebox with nothing else in it...
(The gradient code did work though)
It looks like you are trying to draw directly on the PictureBox control itself.
Instead you should have an Image assigned to the PictureBox and then draw on the image.
Try changing your code as shown below. (Including the click event for testing.)
Note, the PictureBox keeps the reference to the image directly so you don't need a separate screen image in your class, unless you have a different purpose for it.
Also, this uses Bitmap.SetPixel() which is an extremely slow way to set pixels. There is a much faster but slightly more complex way, in these other links:
SetPixel is too slow. Is there a faster way to draw to bitmap?
Work with bitmaps faster in C#
Remember your button click will only draw one pixel at a time.
So be sure to look carefully:
Running my test code within the click event will yield this:
int x = 0;
int y = 0;
public void DigitalGraphicsDisplay(int red, int green, int blue)
{
if (Display.Image == null)
{
Bitmap NewBMP = new Bitmap(Display.ClientRectangle.Width, Display.ClientRectangle.Height);
using (Graphics g = Graphics.FromImage(NewBMP))
{
g.Clear(Color.White);
}
Display.Image = NewBMP;
}
(Display.Image as Bitmap).SetPixel(x, y, Color.FromArgb(red, green, blue));
Display.Invalidate();
x++;
if (x >= Display.Image.Width)
{
x = 0;
y++;
if (y >= Display.Image.Height)
{
y = 0;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
// Temporary code to show that it works (Due to Bitmap.SetPixel() it will be slow)
for (int I = 1; I < Display.ClientRectangle.Width * Display.ClientRectangle.Height; I++)
DigitalGraphicsDisplay((I/255)%255, (I % Display.ClientRectangle.Width) % 255, 127);
}
UPDATE: Per your comment, try this sample code:
private void button1_Click(object sender, EventArgs e)
{
Boolean a = true;
int b = 0;
do
{
DigitalGraphicsDisplay(51, 153, 102);
if (b == 10000)
{
a = false;
}
b = b + 1;
} while (a);
}
public void DigitalGraphicsDisplay(int red, int green, int blue) {
Graphics g = Display.CreateGraphics();
screen.SetPixel(x, y, Color.FromArgb(red, green, blue));
g.DrawImage(screen, 0, 0, screen.Width, screen.Height);
g.Save();
All possible mistakes in one go..
Never use CreateGraphics to draw persistent Graphics! Always either go for the Paint event or draw into the Image.
Graphics.Save does not save any drawn pixels. It saves the state of the Graphics object, which does not contain graphics but is a tool to write into a related bitmap. The state includes scale, rotation, smoothing-mode and then some..
You already write into the Bitmap so you can simply make it your new PictureBox.Image..
Or the PictureBox.BackgroundImage.
And, as I said, you can instead write on top of both that is onto the PBox's surface. For this use the Paint event, Invalidate to trigger it and class level variables to hold the necessary data..
The latter is for graphics that will change a lot, the two former ones are for changes that accumulate.
Control.CreateGraphics is for transient graphics only, like a rubber-band line or a cursor cross..

How can I instantiate large number of buttons in Windows Forms?

I'm developing a theatre reservation software. I'm using Windows Forms, the seats is represented by a 2-dimensioned array. And I draw the buttons as following:
public void DrawSeats()
{
// pnl_seats is a Panel
pnl_seats.Controls.Clear();
// Here I store all Buttons instance, to later add all buttons in one call (AddRange) to the Panel
var btns = new List<Control>();
// Suspend layout to avoid undesired Redraw/Refresh
this.SuspendLayout();
for (int y = 0; y < _seatZone.VerticalSize; y++)
{
for (int x = 0; x < _seatZone.HorizontalSize; x++)
{
// Check if this seat exists
if (IsException(x, y))
continue;
// Construct the button with desired properties. SeatSize is a common value for every button
var btn = new Button
{
Width = SeatSize,
Height = SeatSize,
Left = (x * SeatSize),
Top = (y * SeatSize),
Text = y + "" + x,
Tag = y + ";" + x, // When the button clicks, the purpose of this is to remember which seat this button is.
Font = new Font(new FontFamily("Microsoft Sans Serif"), 6.5f)
};
// Check if it is already reserved
if (ExistsReservation(x, y))
btn.Enabled = false;
else
btn.Click += btn_seat_Click; // Add click event
btns.Add(btn);
}
}
// As said before, add all buttons in one call
pnl_seats.Controls.AddRange(btns.ToArray());
// Resume the layout
this.ResumeLayout();
}
But already with a seat zone of 20 by 20 (400 buttons), it spent almost 1 minute to draw it, and in debug I checked that the lack of performance, is the instantiation of the buttons.
There is a way to make it faster? Perhaps disable all events during the instatiation or another lightweight Control that has the Click event too?
UPDATE:
lbl was a test, the correct is btn, sorry.
UPDATE 2:
Here is the IsException and ExistsReservations methods:
private bool IsException(int x, int y)
{
for (var k = 0; k < _seatsExceptions.GetLength(0); k++)
if (_seatsExceptions[k, 0] == x && _seatsExceptions[k, 1] == y)
return true;
return false;
}
private bool ExistsReservation(int x, int y)
{
for (var k = 0; k < _seatsReservations.GetLength(0); k++)
if (_seatsReservations[k, 0] == x && _seatsReservations[k, 1] == y)
return true;
return false;
}
Suppose that you change your arrays for reservations and exclusions to
public List<string> _seatsExceptions = new List<string>();
public List<string> _seatsReservations = new List<string>();
you add your exclusions and reservations in the list with something like
_seatsExceptions.Add("1;10");
_seatsExceptions.Add("4;19");
_seatsReservations.Add("2;5");
_seatsReservations.Add("5;5");
your checks for exclusions and reservations could be changed to
bool IsException(int x, int y)
{
string key = x.ToString() + ";" + y.ToString();
return _seatsExceptions.Contains(key);
}
bool ExistsReservation(int x, int y)
{
string key = x.ToString() + ";" + y.ToString();
return _seatsReservations.Contains(key);
}
of course I don't know if you are able to make this change or not in your program. However consider to change the search on your array sooner or later.
EDIT I have made some tests, and while a virtual grid of 20x20 buttons works acceptably well (31 millisecs 0.775ms on average), a bigger one slows down noticeably. At 200x50 the timing jumps to 10 seconds (1,0675 on average). So perhaps a different approach is needed. A bound DataGridView could be a simpler solution and will be relatively easy to handle.
I also won't use such a myriad of controls to implement such a thing. Instead you should maybe create your own UserControl, which will paint all the seats as images and reacts on a click event.
To make it a little easier for you i created such a simple UserControl, that will draw all the seats and reacts on a mouse click for changing of the state. Here it is:
public enum SeatState
{
Empty,
Selected,
Full
}
public partial class Seats : UserControl
{
private int _Columns;
private int _Rows;
private List<List<SeatState>> _SeatStates;
public Seats()
{
InitializeComponent();
this.DoubleBuffered = true;
_SeatStates = new List<List<SeatState>>();
_Rows = 40;
_Columns = 40;
ReDimSeatStates();
MouseUp += OnMouseUp;
Paint += OnPaint;
Resize += OnResize;
}
public int Columns
{
get { return _Columns; }
set
{
_Columns = Math.Min(1, value);
ReDimSeatStates();
}
}
public int Rows
{
get { return _Rows; }
set
{
_Rows = Math.Min(1, value);
ReDimSeatStates();
}
}
private Image GetPictureForSeat(int row, int column)
{
var seatState = _SeatStates[row][column];
switch (seatState)
{
case SeatState.Empty:
return Properties.Resources.emptySeat;
case SeatState.Selected:
return Properties.Resources.choosenSeat;
default:
case SeatState.Full:
return Properties.Resources.fullSeat;
}
}
private void OnMouseUp(object sender, MouseEventArgs e)
{
var heightPerSeat = Height / (float)Rows;
var widthPerSeat = Width / (float)Columns;
var row = (int)(e.X / widthPerSeat);
var column = (int)(e.Y / heightPerSeat);
var seatState = _SeatStates[row][column];
switch (seatState)
{
case SeatState.Empty:
_SeatStates[row][column] = SeatState.Selected;
break;
case SeatState.Selected:
_SeatStates[row][column] = SeatState.Empty;
break;
}
Invalidate();
}
private void OnPaint(object sender, PaintEventArgs e)
{
var heightPerSeat = Height / (float)Rows;
var widthPerSeat = Width / (float)Columns;
e.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
for (int row = 0; row < Rows; row++)
{
for (int column = 0; column < Columns; column++)
{
var seatImage = GetPictureForSeat(row, column);
e.Graphics.DrawImage(seatImage, row * widthPerSeat, column * heightPerSeat, widthPerSeat, heightPerSeat);
}
}
}
private void OnResize(object sender, System.EventArgs e)
{
Invalidate();
}
private void ReDimSeatStates()
{
while (_SeatStates.Count < Rows)
_SeatStates.Add(new List<SeatState>());
if (_SeatStates.First().Count < Columns)
foreach (var columnList in _SeatStates)
while (columnList.Count < Columns)
columnList.Add(SeatState.Empty);
while (_SeatStates.Count > Rows)
_SeatStates.RemoveAt(_SeatStates.Count - 1);
if (_SeatStates.First().Count > Columns)
foreach (var columnList in _SeatStates)
while (columnList.Count > Columns)
columnList.RemoveAt(columnList.Count - 1);
}
}
This will currently draw forty rows and columns (so there are 800 seats) and you can click on each seat to change its state.
Here are the images i used:
EmtpySeat:
ChoosenSeat:
FullSeat:
If you anchor this control and resize it or you click on a seat to change its state there can be some minor lacking for the repainting if you further increase the number of rows or columns, but that is still somewhere far below one second. If this still hurts you, you have to improve the paint method and maybe check the ClipRectangle property of the paint event and only paint the really needed parts, but that's another story.
Rather than using actual button controls, just draw the image of the seats then when the user clicks on a seat translate the mouse X,Y coordinates to determine which seat was clicked. This will be more efficient. Of course, the drawback is that you have to write the method to translate x,y coordinates to a seat, but that really isn't that difficult.
EDIT; it has been pointed out to me this will not work in Windows Forms!
Well, you are Sequentially working through it.
if one iteration costs 1 sec, the full process will take 400*1 in time.
Perhaps you should try and make a collection of your objects, and process it 'parallel'.
try the .Net framework (4 and above) 'parallel foreach' method:
http://msdn.microsoft.com/en-s/library/system.threading.tasks.parallel.foreach(v=vs.110).aspx
edit: so, if you have a list buttonnames, you can say
buttonNames.ForEach(x=>CreateButton(x));
while your CreateButton() method is as following:
private Button CreateButton(string nameOfButton) { Button b = new
Button(); b.Text = nameOfButton; //do whatever you want...
return b; }

winform move an image inside a picturebox

I've been trying to do this for a few hours now, but for the life of me I can't make it possible.
What I'm trying to do is simply move the image found within a picture box in a winform application. My image is roughly 1000x1000 pixels and my box is something arbitrary like 400x500, so, for example, when I click the mouse I'd want the image to move 50 to the left. But the image box should remain the same size.
For the life of me, however, I can't get this to work. What I have been able to do is the following:
if (kinectController.hands[0].fingertips.Count == 1)
{
pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
}
This function is for my kinect finger tracking app. So when the application finds a single finder point visiable on the screen, the image is centered. However, I would eventually like the image to move along with my finger movement, which will come once I work out the basic step of moving the image a few pixels to the side.
Any help with this would be appreciated.
I did a little bit of research and apparently moving an image within a PictureBox is no easy task, at the very least I couldn't find anything that would make this possible (not saying there isn't a way to do it though).
However, I came up with a bit of a "workaround", see if this fits your needs. To accomplish this:
Create a Panel control, and size it to however much of the image you
would like to display
Inside that panel place a PictureBox control with your image in it
and set the SizeMode property to AutoSize.
Now, put this code in your form
private bool Dragging;
private int xPos;
private int yPos;
private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { Dragging = false; }
private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
Dragging = true;
xPos = e.X;
yPos = e.Y;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
Control c = sender as Control;
if (Dragging && c!= null) {
c.Top = e.Y + c.Top - yPos;
c.Left = e.X + c.Left - xPos;
}
}
Now whenever you click and drag on the PictureBox, it won't actually move the image within it, but the PictureBox control within the panel. Again, not exactly what you were looking for and I'm not sure how this would convert over to Kinect, but I hope this gets you on the right track.
Not enough reputation to comment but I wanted to add on Ben Black answer if someone ever need more control over the image moving around so you can't move the image past it's borders :
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
Control c = sender as Control;
if (Dragging && c != null)
{
int maxX = pictureBox1.Size.Width * -1 + panel.Size.Width;
int maxY = pictureBox1.Size.Height * -1 + panel.Size.Height;
int newposLeft = e.X + c.Left - xPos;
int newposTop = e.Y + c.Top - yPos;
if (newposTop > 0)
{
newposTop = 0;
}
if (newposLeft > 0)
{
newposLeft = 0;
}
if (newposLeft < maxX)
{
newposLeft = maxX;
}
if (newposTop < maxY)
{
newposTop = maxY;
}
c.Top = newposTop;
c.Left = newposLeft;
}
}

How come the graphics is not drawing onto the panel

I want to draw a grid in my panel. The graphics object (screen) that i created with bitmap isn't drawing in my panel. I tried with debugging to look if the screen wasn't drawing but that wasn't the case.
I tried creating the graphic object from the panel createGraphic method and the parameter painteventargs from the panel paint method. Both times when I used it to draw it with OnPaint it took too long.
public Main()
{
InitializeComponent();
backBuffer = new Bitmap(drawPanel.Width, drawPanel.Height);
screen = Graphics.FromImage(backBuffer);
sizeGridPoints = 2;
lenghtBetweenGridPoints = 10;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
screen.Clear(Color.Black);
DrawGrid();
}
private void DrawGrid()
{
for(int x = lenghtBetweenGridPoints; x < drawPanel.Width; x += lenghtBetweenGridPoints)
{
for(int y = lenghtBetweenGridPoints; y < drawPanel.Height; y+= lenghtBetweenGridPoints)
{
screen.FillEllipse(new SolidBrush(Color.Green), x, y, sizeGridPoints, sizeGridPoints);
}
}
}
If you create a Graphics object from a bitmap, it will draw on this bitmap, not on your user interface. Instead, use the Graphics object from the PaintEventArgs e of your OnPaint method, to draw directly on the form or a control.
e.Graphics.FillEllipse(new SolidBrush(Color.Green), x, y, sizeGridPoints, sizeGridPoints);
You should never create your own Graphics object.
Create your own grid control:
public class GridPanel : Panel
{
public GridPanel()
{
DoubleBuffered = true; // Speeds up drawing, e.g. when panel is resized.
// Set default colors
BackColor = Color.Black;
ForeColor = Color.Green;
}
private int _lenghtBetweenGridPoints = 20;
public int LenghtBetweenGridPoints
{
get { return _lenghtBetweenGridPoints; }
set {
if (value != _lenghtBetweenGridPoints) {
_lenghtBetweenGridPoints = value;
Invalidate(); // Redraw the grid.
}
}
}
private int _sizeGridPoints = 3;
public int SizeGridPoints
{
get {
return _sizeGridPoints;
}
set {
if (value != _sizeGridPoints) {
_sizeGridPoints = value;
Invalidate(); // Redraw the grid.
}
}
}
protected override void OnPaint(PaintEventArgs e)
{
// e.Graphics.Clear(Color.Black); Not necessary. We use the BackColor of the panel.
if (LenghtBetweenGridPoints > 0 && SizeGridPoints > 0) {
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; // Optional.
using (var brush = new SolidBrush(ForeColor)) { // We use the ForeColor of the panel.
for (int x = LenghtBetweenGridPoints; x < Width; x += LenghtBetweenGridPoints) {
for (int y = LenghtBetweenGridPoints; y < Height; y += LenghtBetweenGridPoints) {
e.Graphics.FillEllipse(brush, x, y, SizeGridPoints, SizeGridPoints);
}
}
}
}
}
}
Once it has been compiled, it will automatically appear in toolbox window and you can drag and drop it on your form. You will even be able to edit the properties LenghtBetweenGridPoints and SizeGridPoints in the properties window.
You could also simply use the already available BackColor and ForeColor properties of the panel for the grid. This would allow you to set the colors in the properties window as well. Don't forget to dispose brushes that you have created.
Important: Do not call OnPaint directly. Instead, call the Invalidate or Refresh methods of the object you want to redraw. The point is that Windows decides when to call OnPaint. E.g. if Invalidate is called too frequently (e.g. 5 times in 1/60 seconds), Windows might decide to not call OnPaint every time, as this would create lag. On the other hand, when the user resizes the panel, Windows will call OnPaint automatically. If you restore a window that was minimized, this will re-paint the control as well. Otherwise it would remain black.

Categories