Trouble with memory in C# - c#

I want to draw a loading circle (.gif) on the screen, while the applications is loading something big. But I can't run the circle as fast as I want, because I get memory issues. Does anyone know how to solve these (on 75 ms instead of 1000ms)? And how to remove the circle when done (it doesn't disappear any more).
EDIT: The load function is executed when the window size changes.
public Main()
{
InitializeComponent();
StartUp();
WindowState = FormWindowState.Maximized;
}
bool onrun;
bool done;
System.Threading.Timer timer;
GifImage Circle;
Point center;
void StartUp()
{
onrun = true;
done = false;
timer = new System.Threading.Timer(new System.Threading.TimerCallback(Animate));
timer.Change(0, 500);
}
void Animate(object sender)
{
if (onrun == true)
{
Circle = new GifImage("circleAnim.gif");
Circle.ReverseAtEnd = false;
int width = Screen.PrimaryScreen.Bounds.Width;
int height = Screen.PrimaryScreen.Bounds.Height;
center = new Point((width / 2) - 150, (height / 2) - 150);
onrun = false;
}
else if (done == true)
{
timer.Dispose();
}
Image i = Circle.GetNextFrame();
System.Drawing.Graphics GraphicsObject = Graphics.FromHwnd(IntPtr.Zero);
try
{
GraphicsObject.DrawImage(i, center);
i.Dispose();
GraphicsObject.Dispose();
}
catch { }
}
private void Load(object sender, EventArgs e)
{
int hduizend = 100000;
for (int i = 1; i <= 100000000; i++)
{
hduizend /= 2;
hduizend *= 2;
}
done = true;
}
EDIT2 (error):
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt".
Also the gif image itself is not the problem:
public class GifImage
{
private Image gifImage;
private FrameDimension dimension;
private int frameCount;
private int currentFrame = -1;
private bool reverse;
private int step = 1;
public GifImage(string path)
{
gifImage = Image.FromFile(path);
dimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
frameCount = gifImage.GetFrameCount(dimension);
}
public bool ReverseAtEnd
{
get { return reverse; }
set { reverse = value; }
}
public Image GetNextFrame()
{
currentFrame += step;
if (currentFrame >= frameCount || currentFrame < 1)
{
if (reverse)
{
step *= -1;
currentFrame += step;
}
else
currentFrame = 0;
}
return GetFrame(currentFrame);
}
public Image GetFrame(int index)
{
gifImage.SelectActiveFrame(dimension, index);
return (Image)gifImage.Clone();
}
}

assign the gif to a PictureBox and just show the Picturebox when needed. It will take care of the animation. You just need to take care of when it needs to be shown and of positioning it then.
private PictureBox pictureBox = new PictureBox();
Image animatedPicture = Image.FromFile(path);
...
int width = Screen.PrimaryScreen.Bounds.
int height = Screen.PrimaryScreen.Bounds.Height;
center = new Point((width / 2) - 150, (height / 2) - 150);
pictureBox.Location = center;
pictureBox.Visible = true;

Related

Use a KeyDown inside a Timer_Tick Event

Me and my buddy have been working on this magnifier application and we cannot make it work the way we want it.
The way we would like it to work:
Open app.
Move mouse to area you want magnified.
Hit enter.
Magnifying window moves to (offset) location of mouse and keeps updating that window for that specific location.
Hit enter again to move window to new cursor location.
Right now once i hit enter, the window follows the mouse because it goes into a for loop where it grabs "Cursor.Position". I've tried to save the Cursor.Position value at the "OnkeyDown" event and use it inside the timer loop but that won't work since it "does not exist in current context".
Can anyone see how i can do this?
Thanks in advance!
/Morten
/* O-button zooms out
* I-button zooms in
* Esc-button exits app
* Enter moves magnifying window to new location (doesn't work)
*/
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Magnifier
{
public partial class Form1 : Form
{
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
PictureBox pictureBox1 = new PictureBox();
int zoom = 3; //zoom level
public bool NewZoomLocation = false;
public Form1()
{
{
InitializeComponent();
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.BorderStyle = BorderStyle.FixedSingle;
Controls.Add(pictureBox1);
FormBorderStyle = FormBorderStyle.None;
Timer timer = new Timer();
timer.Interval = 100;
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{ var position = Cursor.Position;
int xlocation = position.X;
int ylocation = position.Y;
{
try
{
var graphics = Graphics.FromImage(printscreen as Image);
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
GC.Collect(); // Force the garbage collector (deals with memory leak)
if (NewZoomLocation == true)
{
var lensbmp = new Bitmap(50, 50); //Bitmap for Zoom window
var i = 0;
var j = 0;
for (int row = xlocation - 25; row < xlocation + 25; row++)
{
j = 0;
for (int column = ylocation - 25; column < ylocation + 25; column++)
{
lensbmp.SetPixel(i, j, printscreen.GetPixel(row, column));
j++;
}
i++;
}
this.pictureBox1.Image = new Bitmap(lensbmp, lensbmp.Width * zoom, lensbmp.Height * zoom);
Size = pictureBox1.Image.Size;
Left = xlocation - 45 * (zoom); //Horisontal position of final zoom window
Top = ylocation + 30; //Vertical position of final zoom window
TopMost = true;
}
}
catch //(Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyValue == 73) // I-button to zoom in
zoom++;
else if (e.KeyValue == 79) // O-button to zoom in
zoom--;
else if (e.KeyValue == 27) // Esc-button to exit
{
Close();
Dispose();
}
else if (e.KeyValue == 13) // Enter-button to choose zoon area
{
NewZoomLocation = true;
}
base.OnKeyDown(e);
}
}
}
I'm not really sure what you want to achieve here, however this should get you in a better place.
First thing first. The use of GC.Collect its because you are trying to plug a memory leak, if you ever create an image, dispose of it.
Given some globals
private readonly PictureBox pictureBox1 = new PictureBox();
private Bitmap _lastBmp = new Bitmap(300, 300);
private Point _position;
public bool NewZoomLocation;
private int zoom = 3; //zoom level
Constructor
public Form1()
{
InitializeComponent();
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.BorderStyle = BorderStyle.FixedSingle;
Controls.Add(pictureBox1);
FormBorderStyle = FormBorderStyle.None;
KeyPreview = true;
Size = _lastBmp.Size;
TopMost = true;
var timer = new Timer();
timer.Interval = 100;
timer.Tick += timer_Tick;
timer.Start();
}
Cleanup
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_lastBmp.Dispose();
_lastBmp = null;
}
Keydown
protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
{
base.OnPreviewKeyDown(e);
switch (e.KeyCode)
{
case Keys.Enter:
NewZoomLocation = true;
_position = Cursor.Position;
break;
case Keys.Up:
zoom++;
break;
case Keys.Down:
zoom--;
break;
case Keys.Escape:
Close();
break;
}
}
Timer
private void timer_Tick(object sender, EventArgs e)
{
if (NewZoomLocation)
{
var w = _lastBmp.Size.Width / zoom;
var h = _lastBmp.Size.Height / zoom;
var x = _position.X - w / 2;
var y = _position.Y - h / 2;
var size = new Size(w, h);
using (var screen = new Bitmap(size.Width, size.Height))
{
using (var g = Graphics.FromImage(screen))
{
g.CopyFromScreen(new Point(x, y), Point.Empty, size);
}
// resize
using (var g = Graphics.FromImage(_lastBmp))
{
g.DrawImage(screen, new Rectangle(new Point(), _lastBmp.Size), new Rectangle(0, 0, w, h), GraphicsUnit.Pixel);
}
}
pictureBox1.Image = _lastBmp;
}
}
There is a lot more that can be done with this, however it should get you started. There is no memory leak anymore, it only grabs a screen shot of what it needs so will be faster.
Good luck

how can I split a panel to clickable segments in c# winform?

I am trying to simulate a LED display board with c# . I need a control which contains 1536 clickable controls to simulate LEDs (96 in width and 16 in Height). I used a panel named pnlContainer for this and user will add 1536 tiny customized panels at runtime. These customized panels should change their color by click event at runtime. Everything works . But adding this number of tiny panels to the container takes long time ( about 10 secs). What is your suggestion to solve this issue? Any tips are appreciated.
this is my custome panel:
public partial class LedPanel : Panel
{
public LedPanel()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (this.BackColor == Color.Black)
{
this.BackColor = Color.Red;
}
else
{
this.BackColor = Color.Black;
}
}
}
}
and this is piece of code which adds tiny panels to the pnlContainer :
private void getPixels(Bitmap img2)
{
pnlContainer.Controls.Clear();
for (int i = 0; i < 96; i++)
{
for (int j = 0; j < 16; j++)
{
Custom_Controls.LedPanel led = new Custom_Controls.LedPanel();
led.Name = i.ToString() + j.ToString();
int lWidth = (int)(pnlContainer.Width / 96);
led.Left = i * lWidth;
led.Top = j * lWidth;
led.Width = led.Height = lWidth;
if (img2.GetPixel(i, j).R>numClear.Value)
{
led.BackColor = Color.Red;
}
else
{
led.BackColor = Color.Black;
}
led.BorderStyle = BorderStyle.FixedSingle;
pnlContainer.Controls.Add(led);
}
}
}
Is there any better approach or better control instead of panelto do this?
I agree with what #TaW recommends. Don't put 1000+ controls on a form. Use some sort of data structure, like an array to keep track of which LEDs need to be lit and then draw them in the Paint event of a Panel.
Here's an example. Put a Panel on a form and name it ledPanel. Then use code similar to the following. I just randomly set the values of the boolean array. You would need to set them appropriately in response to a click of the mouse. I didn't include that code, but basically you need to take the location of the mouse click, determine which array entry needs to be set (or unset) and then invalidate the panel so it will redraw itself.
public partial class Form1 : Form
{
//set these variables appropriately
int matrixWidth = 96;
int matrixHeight = 16;
//An array to hold which LEDs must be lit
bool[,] ledMatrix = null;
//Used to randomly populate the LED array
Random rnd = new Random();
public Form1()
{
InitializeComponent();
ledPanel.BackColor = Color.Black;
ledPanel.Resize += LedPanel_Resize;
//clear the array by initializing a new one
ledMatrix = new bool[matrixWidth, matrixHeight];
//Force the panel to repaint itself
ledPanel.Invalidate();
}
private void LedPanel_Resize(object sender, EventArgs e)
{
//If the panel resizes, then repaint.
ledPanel.Invalidate();
}
private void button1_Click(object sender, EventArgs e)
{
//clear the array by initializing a new one
ledMatrix = new bool[matrixWidth, matrixHeight];
//Randomly set 250 of the 'LEDs';
for (int i = 0; i < 250; i++)
{
ledMatrix[rnd.Next(0, matrixWidth), rnd.Next(0, matrixHeight)] = true;
}
//Make the panel repaint itself
ledPanel.Invalidate();
}
private void ledPanel_Paint(object sender, PaintEventArgs e)
{
//Calculate the width and height of each LED based on the panel width
//and height and allowing for a line between each LED
int cellWidth = (ledPanel.Width - 1) / (matrixWidth + 1);
int cellHeight = (ledPanel.Height - 1) / (matrixHeight + 1);
//Loop through the boolean array and draw a filled rectangle
//for each one that is set to true
for (int i = 0; i < matrixWidth; i++)
{
for (int j = 0; j < matrixHeight; j++)
{
if (ledMatrix != null)
{
//I created a custom brush here for the 'off' LEDs because none
//of the built in colors were dark enough for me. I created it
//in a using block because custom brushes need to be disposed.
using (var b = new SolidBrush(Color.FromArgb(64, 0, 0)))
{
//Determine which brush to use depending on if the LED is lit
Brush ledBrush = ledMatrix[i, j] ? Brushes.Red : b;
//Calculate the top left corner of the rectangle to draw
var x = (i * (cellWidth + 1)) + 1;
var y = (j * (cellHeight + 1) + 1);
//Draw a filled rectangle
e.Graphics.FillRectangle(ledBrush, x, y, cellWidth, cellHeight);
}
}
}
}
}
private void ledPanel_MouseUp(object sender, MouseEventArgs e)
{
//Get the cell width and height
int cellWidth = (ledPanel.Width - 1) / (matrixWidth + 1);
int cellHeight = (ledPanel.Height - 1) / (matrixHeight + 1);
//Calculate which LED needs to be turned on or off
int x = e.Location.X / (cellWidth + 1);
int y = e.Location.Y / (cellHeight + 1);
//Toggle that LED. If it's off, then turn it on and if it's on,
//turn it off
ledMatrix[x, y] = !ledMatrix[x, y];
//Force the panel to update itself.
ledPanel.Invalidate();
}
}
I'm sure there can be many improvements to this code, but it should give you an idea on how to do it.
#Chris and #user10112654 are right.
here is a code similar to #Chris but isolates the displaying logic in a separate class. (#Chris answered your question when I was writing the code :))))
just create a 2D array to initialize the class and pass it to the Initialize method.
public class LedDisplayer
{
public LedDisplayer(Control control)
{
_control = control;
_control.MouseDown += MouseDown;
_control.Paint += Control_Paint;
// width and height of your tiny boxes
_width = 5;
_height = 5;
// margin between tiny boxes
_margin = 1;
}
private readonly Control _control;
private readonly int _width;
private readonly int _height;
private readonly int _margin;
private bool[,] _values;
// call this method first of all to initialize the Displayer
public void Initialize(bool[,] values)
{
_values = values;
_control.Invalidate();
}
private void MouseDown(object sender, MouseEventArgs e)
{
var firstIndex = e.X / OuterWidth();
var secondIndex = e.Y / OuterHeight();
_values[firstIndex, secondIndex] = !_values[firstIndex, secondIndex];
_control.Invalidate(); // you can use other overloads of Invalidate method for the blink problem
}
private void Control_Paint(object sender, PaintEventArgs e)
{
if (_values == null)
return;
e.Graphics.Clear(_control.BackColor);
for (int i = 0; i < _values.GetLength(0); i++)
for (int j = 0; j < _values.GetLength(1); j++)
Rectangle(i, j).Paint(e.Graphics);
}
private RectangleInfo Rectangle(int firstIndex, int secondIndex)
{
var x = firstIndex * OuterWidth();
var y = secondIndex * OuterHeight();
var rectangle = new Rectangle(x, y, _width, _height);
if (_values[firstIndex, secondIndex])
return new RectangleInfo(rectangle, Brushes.Red);
return new RectangleInfo(rectangle, Brushes.Black);
}
private int OuterWidth()
{
return _width + _margin;
}
private int OuterHeight()
{
return _height + _margin;
}
}
public class RectangleInfo
{
public RectangleInfo(Rectangle rectangle, Brush brush)
{
Rectangle = rectangle;
Brush = brush;
}
public Rectangle Rectangle { get; }
public Brush Brush { get; }
public void Paint(Graphics graphics)
{
graphics.FillRectangle(Brush, Rectangle);
}
}
this is how it's used in the form:
private void button2_Click(object sender, EventArgs e)
{
// define the displayer class
var displayer = new LedDisplayer(panel1);
// define the array to initilize the displayer
var display = new bool[,]
{
{true, false, false, true },
{false, true, false, false },
{false, false, true, false },
{true, false, false, false }
};
// and finally
displayer.Initialize(display);
}

C# Snow effect on MDI Container

I have a form set as the IsMdiContainer attribute to true.
I'm trying to make it in the container "snows".
I am trying to adapt a code that works well on a normal WinForms, but not good on MDI container. This is what I managed to do:
public partial class SnowTest : Form
{
int num;
int[] x;
int[] y;
int[] v;
int[] s;
Random random = new Random();
System.Drawing.Graphics graphics;
Rectangle rectangle;
private MdiClient MDIContainer;
private Graphics asd;
public SnowTest()
{
InitializeComponent();
}
private void SnowTest_Load(object sender, EventArgs e)
{
SelectMdiContainer();
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.UpdateStyles();
snow();
Timer1.Start();
}
private void SelectMdiContainer()
{
foreach (Control control in this.Controls)
{
// #2
MdiClient client = control as MdiClient;
if (!(client == null))
{
MDIContainer = client;
break;
}
}
}
private void snow()
{
num = 2000;
x = new int[num];
y = new int[num];
v = new int[num];
s = new int[num];
int i = 0;
for (i = 0; i <= num - 1; i++)
{
Insnow(i);
}
}
private void Insnow(int i)
{
x[i] = random.Next(0, this.Width - 1);
y[i] = random.Next(0, this.Height * 5 / 7);
v[i] = random.Next(5, 20);
s[i] = (random.Next(1, 3) * 100 + random.Next(50, 200)) / 100;
}
private void Timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i <= num - 1; i++)
{
y[i] = y[i] + v[i];
if (y[i] >= this.Height)
{
Insnow(i);
}
}
Invalidate();
SnowOnContainer();
}
private void SnowOnContainer()
{
graphics = MDIContainer.CreateGraphics();;
int i = 0;
for (i = 0; i <= num - 1; i++)
{
graphics.FillEllipse(Brushes.White, x[i], y[i], s[i], s[i]);
}
}
private void SnowTest_Resize(object sender, EventArgs e)
{
rectangle = new Rectangle(0, 0, this.Width, this.Height);
}
}
The Timer1 is set with a Interval of 100
The script runs and generates the "snow" but it does not remove it after a while and also the whole form creates lag.
What is the best way to achieve my goal?
In the normal form is pretty much structured in the same way, it lacks the function that select the container (SelectMdiContainer()), the function SnowOnContainer() and the global variable MDIContainer.
In the form, however, there is the paint event and consequently below carry as structured
private void SnowTest_Paint(object sender, PaintEventArgs e)
{
graphics = e.Graphics;
int i = 0;
for (i = 0; i <= num - 1; i++)
{
graphics.FillEllipse(Brushes.White, x[i], y[i], s[i], s[i]);
}
}
EDIT
I'm doing some tests. Currently I removed the function SnowOnContainer() and added the Paint event for the container.
private void SelectMdiContainer()
{
foreach (Control control in this.Controls)
{
// #2
MdiClient client = control as MdiClient;
if (!(client == null))
{
MDIContainer = client;
MDIContainer.Paint += OnMdiContainerPaint; //Added this Event
break;
}
}
}
The event is structured as that of the normal form but applied to the container
private void OnMdiContainerPaint(object sender, PaintEventArgs e)
{
graphics = MDIContainer.CreateGraphics();
int i = 0;
for (i = 0; i <= num - 1; i++)
{
graphics.FillEllipse(Brushes.White, x[i], y[i], s[i], s[i]);
}
}
Finally I did some research and I've added this code to avoid Flickering animation. as shown in this topic How to fix the flickering in User controls
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000; // Turn on WS_EX_COMPOSITED
return cp;
}
}
In doing so it appears to be working properly with a fluid animation, but as soon as I resize the form, or I reduce to an icon returns lag

How to render tiles efficiently using Graphics.Draw?

I am currently making a tile-based game in c#, but every time I draw the tiles it uses a lot of CPU, and as the tiles get bigger(if i make the game full screen) it consumes even more.
This is my Tile class:
public class Tiles
{
//PRIVATE :
//variabiles
private int XPosition, YPosition;
private Image Texture;
private bool Colidable;
private int SizeW = 32;
private int SizeH = 32;
private Resizer resizer = new Resizer();
//methods
//PUBLIC :
//variabiles
//methods
//CONSTRUCTOR
public Tiles(int _x,int _y,Image _i, int _sW = 32, int _sH = 32, bool _c = false)
{
XPosition = _x;//set position X
YPosition = _y;//set position Y
SizeW = _sW;
SizeH = _sH;
Texture = resizer.ResizeImage(_i, SizeW, SizeH) ;// set texture
Colidable = _c;//set if the tile is colidable,default : false
resizer = null;
}
//DRAW METHOD
//gets graphics object to draw on, adn draws at the position of the tile
public void Draw(Graphics _g)
{
_g.DrawImage(this.Texture, this.XPosition, this.YPosition);
}
//GET PRIVATE MEBERS
//returns if the tile is colidable
public bool getColidable()
{
return this.Colidable;
}
}
and this is how I draw the tiles:
private void DrawMap(Graphics _g)
{
//CALLS THE DRAW METHOD OF EACH TILE
for (int i = 0; i < MAP_WIDTH; i++)
{
for (int j = 0; j < MAP_HEIGHT; j++)
{
Tile[i, j].Draw(_g);
}
}
}
bool TilesUpdate = false;
private void _Window_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(Color.Black);
if (isGameRunning)
{
DrawMap(e.Graphics);
}
else
{
FullRezolutionBtn.Draw(e.Graphics);
BigRezolutionBtn.Draw(e.Graphics);
NormalRezolutionBtn.Draw(e.Graphics);
}
}
private void Update_Tick(object sender, EventArgs e)
{
Invalidate();
}
I want to mention that the map is 20 x 20 tiles and it's cosuming around 50% of the cpu when it's fullscreen.
As I mentioned in the comments, the direction should be to do less painting. One way is to invalidate and paint portions of the drawing canvas only when something related to that portion changes. Windows itself does such optimization for controls/windows.
Here is an example. Look how Gadget class invalidates it's rectangle when some property changes. Then during the paint, only rectangles that intersect with e.ClipRectange are drawn. This highly reduces the number of the drawing operations.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Samples
{
class Gadget
{
public readonly Control Canvas;
public Gadget(Control canvas) { Canvas = canvas; }
private Rectangle bounds;
public Rectangle Bounds
{
get { return bounds; }
set
{
if (bounds == value) return;
// NOTE: Invalidate both old and new rectangle
Invalidate();
bounds = value;
Invalidate();
}
}
private Color color;
public Color Color
{
get { return color; }
set
{
if (color == value) return;
color = value;
Invalidate();
}
}
public void Invalidate()
{
Canvas.Invalidate(bounds);
}
public void Draw(Graphics g)
{
using (var brush = new SolidBrush(color))
g.FillRectangle(brush, bounds);
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new Form { WindowState = FormWindowState.Maximized };
int rows = 9, cols = 9;
var gadgets = new Gadget[rows, cols];
var rg = new Random();
Color[] colors = { Color.Yellow, Color.Blue, Color.Red, Color.Green, Color.Magenta };
int size = 64;
var canvas = form;
for (int r = 0, y = 8; r < rows; r++, y += size)
for (int c = 0, x = 8; c < cols; c++, x += size)
gadgets[r, c] = new Gadget(canvas) { Color = colors[rg.Next(colors.Length)], Bounds = new Rectangle(x, y, size, size) };
int paintCount = 0, drawCount = 0;
canvas.Paint += (sender, e) =>
{
paintCount++;
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
if (e.ClipRectangle.IntersectsWith(gadgets[r, c].Bounds))
{
gadgets[r, c].Draw(e.Graphics);
drawCount++;
}
}
}
form.Text = $"Paint:{paintCount} Draw:{drawCount} of {(long)paintCount * rows * cols}";
};
var timer = new Timer { Interval = 100 };
timer.Tick += (sender, e) =>
{
gadgets[rg.Next(rows), rg.Next(cols)].Color = colors[rg.Next(colors.Length)];
};
timer.Start();
Application.Run(form);
}
}
}
Not sure how your resizer class works. i think there is problem when you re-size every image every time.
Texture = resizer.ResizeImage(_i, SizeW, SizeH) ;// set texture
i would replace above line like this
Texture = _i;// set texture but do not resize image now
at the same time update the Draw Function of Tile like below.
public void Draw(Graphics _g)
{
//now specify the location and size of the image.
_g.DrawImage(Texture , new Rectangle(this.XPosition, this.YPosition, SizeW, SizeH));
}
hopefully it should improve the performance.
if it flicker then you can use Double Buffer

Drawing background image into form overflow client area

I have a problem with drawing image on form background. I have a form where there are inserted both scrollbars (H and V). Because I need to be able display image in original size I use them for scrolling it but when I scroll to maximum right or bottom on both sides missing 7 pixels which are hidden under scrollbars. There is sample code:
private int PosX, PosY;
this.Map = new Bitmap(TestLines.Properties.Resources.mapa);
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
if (this.Map != null)
{
e.Graphics.DrawImageUnscaled(Map, new Point(this.PosX, this.PosY));
int MapResX = (int)((float)this.Map.Width / this.Map.HorizontalResolution * e.Graphics.DpiX);
int MapResY = (int)((float)this.Map.Height / this.Map.VerticalResolution * e.Graphics.DpiY);
if (MapResX > this.ClientSize.Width && MapResY > this.ClientSize.Height - this.toolStrip1.Height)
{
hScrollBar1.Minimum = 0;
hScrollBar1.Maximum = MapResX - this.ClientSize.Width + vScrollBar1.Width;
hScrollBar1.Visible = true;
vScrollBar1.Minimum = 0;
vScrollBar1.Maximum = MapResY - this.ClientSize.Height + toolStrip1.Height + hScrollBar1.Height;
vScrollBar1.Visible = true;
}
else if (MapResX > this.ClientSize.Width)
{
hScrollBar1.Minimum = 0;
hScrollBar1.Maximum = MapResX - this.ClientSize.Width;
hScrollBar1.Visible = true;
vScrollBar1.Visible = false;
}
else if (MapResY > this.ClientSize.Height - this.toolStrip1.Height)
{
vScrollBar1.Minimum = 0;
vScrollBar1.Maximum = MapResY - this.ClientSize.Height + toolStrip1.Height;
vScrollBar1.Visible = true;
hScrollBar1.Visible = false;
}
else
{
hScrollBar1.Visible = false;
vScrollBar1.Visible = false;
}
}
}
Note that there is also a toolstrip where i do not draw. And then simple scrollbars actions:
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
this.PosX = -e.NewValue;
this.Invalidate(false);
this.Update();
}
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
this.PosY = toolStrip1.Height -e.NewValue;
this.Invalidate(false);
this.Update();
}
Can you describe me why this happens ?
This is just not the right way to go about it. Create your own control instead, using Panel as the base class so you get the scrolling for free. Add a new class to your project and paste the code shown below. Compile. Drop it from the top of the toolbox onto your form, you probably want to set its Dock property to Fill. Assign the Map property, either with the designer or in your code.
using System;
using System.Drawing;
using System.Windows.Forms;
class MapPanel : Panel {
public MapPanel() {
this.DoubleBuffered = true;
this.ResizeRedraw = true;
}
private Image map;
public Image Map {
get { return map; }
set {
map = value;
this.AutoScrollMinSize = value == null ? Size.Empty : value.Size;
this.Invalidate();
}
}
protected override void OnPaintBackground(PaintEventArgs e) {
base.OnPaintBackground(e);
if (map != null) {
e.Graphics.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);
e.Graphics.DrawImage(map, 0, 0);
}
}
}

Categories