using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace MultiPaint
{
public partial class PaintForm : Form
{
//Bitmap which contains the "painting"
Bitmap picture = new Bitmap(1,1);
public PaintForm()
{
picture.SetPixel(0, 0, Color.White);
InitializeComponent();
}
/// <summary>
/// Updates the bitmap's size and copy old content (mostly for future purposes)
/// </summary>
public void SetSize(int width, int height)
{
lock (this)
{
if (picture.Width != width || picture.Height != height)
{
Bitmap newPicture = new Bitmap(width != -1 ? width : picture.Width, height != -1 ? height : picture.Height);
Graphics newPictureGraphics = Graphics.FromImage(newPicture);
newPictureGraphics.FillRectangle(new SolidBrush(Color.White), 0, 0, newPicture.Width, newPicture.Height);
newPictureGraphics.DrawImage(picture, 0, 0);
newPictureGraphics.Dispose();
picture.Dispose();
picture = newPicture;
}
}
}
/// <summary>
/// Sets a pixel's color
/// </summary>
public bool SetPixel(int x, int y, Color color)
{
lock (this)
{
try
{
picture.SetPixel(x, y, color);
}
catch
{
return false;
}
UpdateView();
return true;
}
}
/// <summary>
/// Writes the current image into a stream
/// </summary>
public MemoryStream SaveImage(ImageFormat format)
{
MemoryStream stream = new MemoryStream();
Bitmap scaledPicture = new Bitmap(picture.Width * 5, picture.Height * 5);
Graphics scaledPictureGraphics = Graphics.FromImage(scaledPicture);
scaledPictureGraphics.DrawImage(picture, 0, 0, scaledPicture.Width, scaledPicture.Height);
scaledPictureGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
scaledPictureGraphics.DrawImage(picture, 0, 0, scaledPicture.Width, scaledPicture.Height);
scaledPictureGraphics.Dispose();
scaledPicture.Save(stream, format);
scaledPicture.Dispose();
return stream;
}
void UpdateView()
{
this.Invoke(new UpdateViewActionDelegate(UpdateViewAction));
}
delegate void UpdateViewActionDelegate();
void UpdateViewAction()
{
if (ClientSize.Width != picture.Width * 5 || ClientSize.Height != picture.Height * 5)
ClientSize = new Size(picture.Width * 5, picture.Height * 5);
if(this.Visible)
Invalidate();
}
private void PaintForm_Paint(object sender, PaintEventArgs e)
{
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
e.Graphics.DrawImage(picture, 0, 0, ClientSize.Width, ClientSize.Height);
}
private void PaintForm_FormClosing(object sender, FormClosingEventArgs e)
{
//Only the hide the form if it was closed by the user
if (e.CloseReason == CloseReason.UserClosing)
{
this.Visible = false;
e.Cancel = true;
}
}
private void PaintForm_Shown(object sender, EventArgs e)
{
try
{
//Sets the form's size to a small default
SetSize(5, 5);
}
catch { }
}
}
}