Shapes not visible while drawing on mouse drag C# - visual-studio-2005

I'm a new developer.I'm trying to make a simple program in which we can draw multiple shapes like Rectangle, Ellipse, Line, etc. The problem which I'm facing right now is that when I click the mouse and drag to draw on mouseDown and mouseMove event I'm not able to see the shape. The shape appears on the pictureBox only when I leave the mouse.
I want the shape to appear and move with the mouse as the user draws it just like in paint application by Microsoft.
I tried using Refresh() function while drawing but it removes the old shapes which was already drawn in the pictureBox.
Below is the code I'm using. need some suggestions.
bool draw = false;
bool isMouseDown = false;
int x, y, lx, ly = 0;
Item currItem;
Pen pen = new Pen(Color.Red,1);
public enum Item
{
Rectangle, Ellipse, Line, Pencil, Eraser
}
private void btnROIDraw_Click(object sender, EventArgs e)
{
if (menuStripRoi.Visible == false)
{
menuStripRoi.Visible = true;
}
else
{
menuStripRoi.Visible = false;
draw = false;
}
}
private void pictureBoxROI_MouseDown(object sender, MouseEventArgs e)
{
x = e.X;
y = e.Y;
isMouseDown = true;
//draw = true;
}
private void pictureBoxROI_MouseUp(object sender, MouseEventArgs e)
{
lx = e.X;
ly = e.Y;
if (draw)
{
Graphics g = pictureBoxROI.CreateGraphics();
switch (currItem)
{
case Item.Rectangle:
g.DrawRectangle(pen, x, y, e.X - x, e.Y - y);
break;
case Item.Ellipse:
g.DrawEllipse(pen, x, y, e.X - x, e.Y - y);
break;
case Item.Line:
g.DrawLine(pen, x, y, e.X, e.Y);
break;
}
g.Dispose();
}
isMouseDown = false;
}
private void pictureBoxROI_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
if (draw)
{
Graphics g = pictureBoxROI.CreateGraphics();
switch (currItem)
{
case Item.Pencil:
g.FillEllipse(new SolidBrush(Color.Red), e.X - x + x, e.Y - y + y, 2, 2);
break;
case Item.Eraser:
g.FillEllipse(new SolidBrush(pictureBoxROI.BackColor), e.X - x + x, e.Y - y + y, 20, 20);
break;
}
g.Dispose();
}
}
}
private void pictureBoxROI_Paint(object sender, PaintEventArgs e)
{
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
pictureBoxROI.Refresh();
}
private void rectangleToolStripMenuItem_Click(object sender, EventArgs e)
{
currItem = Item.Rectangle;
draw = true;
}
private void ellipseToolStripMenuItem_Click(object sender, EventArgs e)
{
currItem = Item.Ellipse;
draw = true;
}
private void lineToolStripMenuItem_Click(object sender, EventArgs e)
{
currItem = Item.Line;
draw = true;
}
private void pencilToolStripMenuItem_Click(object sender, EventArgs e)
{
currItem = Item.Pencil;
draw = true;
}
private void eracerToolStripMenuItem_Click(object sender, EventArgs e)
{
currItem = Item.Eraser;
draw = true;
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
pictureBoxROI.Refresh();
pictureBoxROI.Image = null;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog o = new OpenFileDialog();
o.Filter = "Png files|*.png|jpeg files|*jpg|bitmaps|*.bmp";
if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pictureBoxROI.Image = (Image)Image.FromFile(o.FileName).Clone();
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(pictureBoxROI.Width, pictureBoxROI.Height);
Graphics g = Graphics.FromImage(bmp);
Rectangle rect = pictureBoxROI.RectangleToScreen(pictureBoxROI.ClientRectangle);
g.CopyFromScreen(rect.Location, Point.Empty, pictureBoxROI.Size);
g.Dispose();
SaveFileDialog s = new SaveFileDialog();
s.Filter = "Png files|*.png|jpeg files|*jpg|bitmaps|*.bmp";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (File.Exists(s.FileName))
{
File.Delete(s.FileName);
}
if (s.FileName.Contains(".jpg"))
{
bmp.Save(s.FileName, ImageFormat.Jpeg);
}
else if (s.FileName.Contains(".png"))
{
bmp.Save(s.FileName, ImageFormat.Png);
}
else if (s.FileName.Contains(".bmp"))
{
bmp.Save(s.FileName, ImageFormat.Bmp);
}
}
}

Found a solution to my question.
This article explains in detail everything about drawing with GDI+. Worth having a look
http://www.codeproject.com/Articles/17893/Extensions-to-DrawTools

Related

Visual Studio 2022 C++ How to make a calculator with 2 textboxes to accept ONLY numbers

textBox3 is just the result textBox , all i want is a validation check for textBox1 and textBox2 so the only input is numbers
#pragma endregion
private: System::Void Calculate(System::Object^ sender, System::EventArgs^ e) {
if (sender == button_plus) {
textBox3->Text = Convert::ToString(Convert::ToDouble(textBox1->Text) + Convert::ToDouble(textBox2->Text));
}
else if (sender == button_minus) {
textBox3->Text = Convert::ToString(Convert::ToDouble(textBox1->Text) - Convert::ToDouble(textBox2->Text));
}
else if (sender == button_multi) {
textBox3->Text = Convert::ToString(Convert::ToDouble(textBox1->Text) * Convert::ToDouble(textBox2->Text));
}
else if (sender == button_div) {
textBox3->Text = Convert::ToString(Convert::ToDouble(textBox1->Text) / Convert::ToDouble(textBox2->Text));
}
else if (sender == button_exit) {
this->Close();
}
}
I fianlly figured it out i just make a try, catch and solve this one
private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e) {
double num1;
try {
num1 = System::Double::Parse(this->textBox1->Text);
}
catch (System::Exception^ exception) {
num1 = 0;
}
this->textBox1->Text = num1.ToString();}
private: System::Void textBox2_TextChanged(System::Object^ sender, System::EventArgs^ e) {
double num2;
try {
num2 = System::Double::Parse(this->textBox2->Text);
}
catch (System::Exception^ exception) {
num2 = 0;
}
this->textBox2->Text = num2.ToString();}

Frame border disappears from ViewCell while listview scroll up and down in Xamarin form android

I have set list border using trigger according to my requirement but when I scroll up the listview and selected view cell is gone than I scroll down when ViewCell is appearing on screen than selected border is gone
To prevent this I also created frame renderer but still ViewCell border gone.
Attached image here
class FrameHighLightRenderer : VisualElementRenderer<Frame>
{
ACanvas _canvas = null;
private FrameDrawable _frameDrawable;
protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (_frameDrawable != null && e.NewElement.ClassId != null) //This block execute while any cell appearing in scroll time up/dowm
{ // I added classId =10 to identify colored/selected cell
if (e.NewElement.ClassId=="10")
{
e.NewElement.OutlineColor = Xamarin.Forms.Color.Red;
this.Invalidate();
}
else
{
e.NewElement.BackgroundColor = Xamarin.Forms.Color.TransParent;
}
}
else
{
UpdateBackground();
}
}
}
void UpdateBackground()
{
_frameDrawable = new FrameDrawable(Element, Context.ToPixels);
this.SetBackground(_frameDrawable);
}
class FrameDrawable : Drawable
{
readonly Frame _frame;
readonly Func<double, float> _convertToPixels;
public ACanvas _canvas;
bool _isDisposed;
Bitmap _normalBitmap;
public FrameDrawable(Frame frame, Func<double, float> convertToPixels)
{
_frame = frame;
_convertToPixels = convertToPixels;
frame.PropertyChanged += FrameOnPropertyChanged;
}
public override bool IsStateful
{
get { return false; }
}
public override int Opacity
{
get { return 0; }
}
public override void Draw(ACanvas canvas)
{
SetBorderColorandWidth(canvas);
}
private void SetBorderColorandWidth(ACanvas canvas)
{
int width = Bounds.Width();
int height = Bounds.Height();
if (width <= 0 || height <= 0)
{
if (_normalBitmap != null)
{
_normalBitmap.Dispose();
_normalBitmap = null;
}
return;
}
if (_normalBitmap == null || _normalBitmap.Height != height || _normalBitmap.Width != width)
{
_normalBitmap = CreateBitmap(false, width, height);
}
Bitmap bitmap = _normalBitmap;
// if(canvas)
if (InspectionQAPage._highlight_color)
{
using (var paint = new Paint { AntiAlias = true })
using (var path = new Path())
using (Path.Direction direction = Path.Direction.Cw)
using (Paint.Style style = Paint.Style.Stroke)
using (var rect = new RectF(0, 0, width, height))
{
float rx = Forms.Context.ToPixels(4);
float ry = Forms.Context.ToPixels(4);
path.AddRoundRect(rect, rx, ry, direction);
if (this._frame.OutlineColor == Xamarin.Forms.Color.Red)
{
paint.Color = Android.Graphics.Color.Red;
this._frame.ClassId = "10";
// this._frame.BackgroundColor = Xamarin.Forms.Color.Red;
// paint.SetStyle = (Paint.Style)(Resource.Style.WithBorder);
}
else
{
// paint.Reset();
paint.Color = Android.Graphics.Color.Transparent;
// this._frame.BackgroundColor = Xamarin.Forms.Color.Transparent;
}
paint.StrokeWidth = 10f; //set outline stroke
paint.SetStyle(style);
canvas.DrawPath(path, paint);
}
InspectionQAPage._highlight_color = false;
}
else
{
using (var paint = new Paint())
canvas.DrawBitmap(bitmap, 0, 0, paint);
}
// InvalidateSelf();
}
public override void SetAlpha(int alpha)
{
}
public override void SetColorFilter(ColorFilter cf)
{
}
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
if (_normalBitmap != null)
{
_normalBitmap.Dispose();
_normalBitmap = null;
}
_isDisposed = true;
}
base.Dispose(disposing);
}
protected override bool OnStateChange(int[] state)
{
return false;
}
Bitmap CreateBitmap(bool pressed, int width, int height)
{
Bitmap bitmap;
using (Bitmap.Config config = Bitmap.Config.Argb8888)
if (width <= 0 || height <= 0)
{
return null;
}
else
bitmap = Bitmap.CreateBitmap(width, height, config);
using (var canvas = new ACanvas(bitmap))
{
// DrawCanvas(canvas, width, height, pressed);
}
return bitmap;
}
void FrameOnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName ||
e.PropertyName == Frame.OutlineColorProperty.PropertyName ||
e.PropertyName == Frame.CornerRadiusProperty.PropertyName)
{
try
{
if (_normalBitmap == null)
return;
int width = Bounds.Width();
int height = Bounds.Height();
if (width <= 0 || height <= 0)
{
return;
}
if (_canvas == null)
{
var canvas = new ACanvas(_normalBitmap);
_canvas = canvas;
_canvas.DrawColor(global::Android.Graphics.Color.Red, PorterDuff.Mode.Clear);
DrawCanvas(_canvas, width, height, false, sender);
}
else
{
_canvas.DrawColor(global::Android.Graphics.Color.Red, PorterDuff.Mode.Clear);
DrawCanvas(_canvas, width, height, false, sender);
}
InvalidateSelf();
}
catch (Exception ex)
{
Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>" + ex);
throw;
}
}
}
public void DrawCanvas(ACanvas canvas, int width, int height, bool pressed, object sender)
{
using (var paint = new Paint { AntiAlias = true })
using (var path = new Path())
using (Path.Direction direction = Path.Direction.Cw)
using (Paint.Style style = Paint.Style.Stroke)
using (var rect = new RectF(0, 0, width, height))
{
float rx = Forms.Context.ToPixels(4);
float ry = Forms.Context.ToPixels(4);
path.AddRoundRect(rect, rx, ry, direction);
if (((Frame)sender).OutlineColor == Xamarin.Forms.Color.Red)
{
paint.Color = Android.Graphics.Color.Red;
((Frame)sender).ClassId = "10";
}
else
{
((Frame)sender).BackgroundColor = Xamarin.Forms.Color.Transparent;
}
paint.StrokeWidth = 10f; //set outline stroke
paint.SetStyle(style);
canvas.DrawPath(path, paint);
}
}
}
}
}

How to see textbox entry from one form in another form

I am trying to pass the textBox1 value from Form5 to Form1. However it does not seem to remember or see the value when it gets to Form1. I want paf_path to be what paf_path2 is.
System::Void Form5::button1_Click(System::Object^ sender, System::EventArgs^ e) {
System::String^ paf_path2 = textBox1->Text;
FolderBrowserDialog^ folderBrowserDialog1;
folderBrowserDialog1 = gcnew System::Windows::Forms::FolderBrowserDialog;
folderBrowserDialog1->Description = L"Select the directory of your MAF files ";
folderBrowserDialog1->ShowNewFolderButton = false;
// Show the FolderBrowserDialog.
System::Windows::Forms::DialogResult result = folderBrowserDialog1->ShowDialog();
if (result == ::DialogResult::OK)
{
paf_path2 = folderBrowserDialog1->SelectedPath;
}
textBox1->Text = paf_path2;
}
System::Void Form5::button2_Click(System::Object^ sender, System::EventArgs^ e){
Form1 ^dos3 = gcnew Form1(this);
dos3->Show();
this->Hide();
}
System::Void Form1::button1_Click(System::Object^ sender, System::EventArgs^ e) {
System::String^ test = textBox1->Text;
if (test == "")
{
MessageBox::Show("Please enter partial address!");
}
else
{
Form5^doss = gcnew Form5(this);
System::String^ paf_path2 = doss->textBox1->Text;
char* paf_path = (char*) (void*) Marshal::StringToHGlobalAnsi(paf_path2);

how to save an image on a panel to a image file?

This program should work like join the dots , the user selects the number of dots to display and is able to draw on the canvas, the problem is with the save , whenever i try to save it isnt working at all , it gives me a black rectangle..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Painting2
{
public partial class Form1 : Form
{
Bitmap drawing;
bool draw = false;
Color C = Color.Black;
int size = 14;
bool startdraw = false;
public Form1(string parameter1)
{
InitializeComponent();
this.Text = parameter1;
}
private void Form1_Load(object sender, EventArgs e)
{
drawing = new Bitmap (pnlcanvas.Width, pnlcanvas.Height, pnlcanvas.CreateGraphics());
cbdots.Items.Add("2");
cbdots.Items.Add("3");
cbdots.Items.Add("4");
cbdots.Items.Add("5");
cbdots.Items.Add("6");
cbdots.Items.Add("7");
cbdots.Items.Add("8");
cbdots.Items.Add("9");
cbdots.Items.Add("10");
cbdots.Items.Add("11");
cbdots.Items.Add("12");
cbdots.Items.Add("13");
cbdots.Items.Add("14");
cbdots.Items.Add("15");
}
private void pnlcanvas_MouseDown(object sender, MouseEventArgs e)
{
draw = true;
Graphics g = Graphics.FromImage(drawing);
SolidBrush b = new SolidBrush(C);
if (startdraw == true)
{
g.FillEllipse(b, e.X, e.Y, size, size);
pnlcanvas.CreateGraphics().DrawImageUnscaled(drawing, new Point(0, 0));
}
}
private void pnlcanvas_MouseUp(object sender, MouseEventArgs e)
{
draw = false;
}
private void pnlcanvas_Move(object sender, EventArgs e)
{
}
private void pnlcanvas_MouseMove(object sender, MouseEventArgs e)
{
if (draw == true && startdraw == true)
{
Graphics g = Graphics.FromImage(drawing);
SolidBrush b = new SolidBrush(C);
g.FillEllipse(b, e.X, e.Y, size, size);
pnlcanvas.CreateGraphics().DrawImageUnscaled(drawing, new Point(0, 0));
}
}
private void btncolor_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
C = Color.White;
size = 25;
}
private void button2_Click(object sender, EventArgs e)
{
drawing = new Bitmap(pnlcanvas.Width, pnlcanvas.Height, pnlcanvas.CreateGraphics());
pnlcanvas.CreateGraphics().Clear(Color.White);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void btnsave_Click(object sender, EventArgs e)
{
//if (saveDialog.ShowDialog() == DialogResult.OK)
//{
// Bitmap tosave = new Bitmap(pnlcanvas.Width, pnlcanvas.Height);
// pnlcanvas.DrawToBitmap(tosave, new Rectangle(0, 0, pnlcanvas.Width, pnlcanvas.Height));
// tosave.Save(saveDialog.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
//}
using (Bitmap bitmap = new Bitmap(pnlcanvas.ClientSize.Width,
pnlcanvas.ClientSize.Height))
{
pnlcanvas.DrawToBitmap(bitmap, pnlcanvas.ClientRectangle);
bitmap.Save(#"C:\Users\xejns_000\Desktop\TestDrawToBitmap.bmp", ImageFormat.Bmp);
}
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void btnstart_Click(object sender, EventArgs e)
{
DialogResult result = cd.ShowDialog();
if (result == DialogResult.OK)
{
C = cd.Color;
}
startdraw = true;
}
private void cbdots_SelectedIndexChanged(object sender, EventArgs e)
{
drawing = new Bitmap(pnlcanvas.Width, pnlcanvas.Height, pnlcanvas.CreateGraphics()); //clearing
pnlcanvas.CreateGraphics().Clear(Color.White); //clearing
Random r = new Random();
for (int i = 0; i <= Convert.ToInt32(cbdots.SelectedItem.ToString()) -1; i++)
{
Color RandC = Color.Black; ;
int randomcolor = r.Next(1, 11);
int randomx = r.Next(10, 730);
int randomy = r.Next(10, 390);
switch (randomcolor) // choosing random color
{
case 1:
RandC = Color.PaleVioletRed;
break;
case 2:
RandC = Color.PowderBlue;
break;
case 3:
RandC = Color.Fuchsia;
break;
case 4:
RandC = Color.DarkGoldenrod;
break;
case 5:
RandC = Color.LavenderBlush;
break;
case 6:
RandC = Color.Tomato;
break;
case 7:
RandC = Color.SpringGreen;
break;
case 8:
RandC = Color.Wheat;
break;
case 9:
RandC = Color.Salmon;
break;
case 10:
RandC = Color.LightSteelBlue;
break;
}
Graphics g = Graphics.FromImage(drawing); // painting dots
SolidBrush b = new SolidBrush(RandC); // painting dots
g.FillEllipse(b, randomx, randomy, 40, 40); // painting dots
pnlcanvas.CreateGraphics().DrawImageUnscaled(drawing, new Point(0, 0));
}
}
}
}

No suitable method found in my overriden methods mono for android

I'm trying to draw a line based on touch event. Basically it draws line as the finger moves. I'm getting an error when overriding ontouchevent and onsizechanged. It was originally written in JAVA. I just translated it to C#. Here's the code:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
currentLevel = Intent.GetIntExtra("gameLevel", 0);
playerScore = Intent.GetIntExtra("score", 0);
SetContentView(new SampleView(this));
// Create your application here
}
private class SampleView : View
{
private Paint mPaint;
private static Bitmap m_bitmap;
private DisplayMetrics m_metrics;
private Canvas m_canvas;
private Path m_path;
private Paint m_bitmapPaint;
private float m_X, m_Y;
static bool m_pathDrawn = false;
private static float TOUCH_TOLERANCE = 4;
public SampleView(Context context)
: base(context)
{
Focusable = true;
mPaint = new Paint();
mPaint.AntiAlias = true;
mPaint.Dither = true;
mPaint.SetStyle(Paint.Style.Stroke);
mPaint.StrokeWidth = 12;
mPaint.StrokeJoin = Paint.Join.Round;
mPaint.StrokeCap = Paint.Cap.Round;
m_metrics = context.Resources.DisplayMetrics;
m_bitmap = Bitmap.CreateBitmap(m_metrics.WidthPixels, m_metrics.HeightPixels, Bitmap.Config.Argb8888);
m_canvas = new Canvas(m_bitmap);
m_bitmapPaint = new Paint();
}
public void onerase()
{
m_canvas = null;
}
protected override void onSizeChanged(int p_w, int p_h, int p_oldw, int p_oldh)
{
this.onSizeChanged(p_w, p_h, p_oldw, p_oldh);
}
protected override void OnDraw(Canvas canvas)
{
canvas.DrawColor(Color.Black);
canvas.DrawBitmap(m_bitmap, 0, 0, m_bitmapPaint);
canvas.DrawPath(m_path, mPaint);
}
private void touch_start(float p_x, float p_y)
{
m_path.Reset();
m_path.MoveTo(p_x, p_y);
m_X = p_x;
m_Y = p_y;
}
private void touch_move(float p_x, float p_y)
{
float m_dx = Math.Abs(p_x - m_X);
float m_dy = Math.Abs(p_y - m_Y);
if (m_dx >= TOUCH_TOLERANCE || m_dy >= TOUCH_TOLERANCE)
{
m_path.QuadTo(m_X, m_Y, (p_x + m_X) / 2, (p_y + m_Y) / 2);
m_X = p_x;
m_Y = p_y;
m_pathDrawn = true;
}
}
private void touch_up()
{
m_path.LineTo(m_X, m_Y);
// commit the path to our offscreen
m_canvas.DrawPath(m_path, mPaint);
// kill this so we don't double draw
m_path.Reset();
}
public override bool onTouchEvent(MotionEvent p_event)
{
float m_x = p_event.GetX();
float m_y = p_event.GetY();
switch (p_event.Action)
{
case MotionEventActions.Down:
touch_start(m_x, m_y);
Invalidate();
break;
case MotionEventActions.Move:
touch_move(m_x, m_y);
Invalidate();
break;
case MotionEventActions.Up:
touch_up();
Invalidate();
break;
}
return true;
}
}
Another thing. I want to make my image view from a layout as my canvas and draw the line there ontouchevent. How should I do this? Thanks!
Method name should use pascal casing.
Android.Views.View.OnTouchEvent Method
Android.Views.View.OnSizeChanged Method
public override bool OnTouchEvent(MotionEvent e)
{
}
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
}
Mono coding guidelines.

Resources