I want to detect mouse click on my custom created region.
1) I ve tried this code with rectangle and it worked, but with string it doesnt
GraphicsPath gp = new GraphicsPath();
Region reg = new Region();
private void Form1_Load(object sender, EventArgs e)
{
gp.AddString("TEXT", new FontFamily("Arial"),0, 20.0f, new Point(300, 10), StringFormat.GenericDefault);
gp.Widen(Pens.AliceBlue);
reg = new Region(gp);
}
and here is the part2
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
if (reg.IsVisible(e.Location))
{
MessageBox.Show("aaaa");
}
}
It doesnt show the message box. :)
EDIT :here is my Paint event to see where my string is
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawString("TEXT", new Font("Arial", 20), Brushes.Yellow, 300,100 );
}
The most basic error is a typo: One time you draw at y = 10, the other time at y = 100.
But there is another issue which is not so obvious at all:
Add
e.Graphics.FillPath(Brushes.Firebrick, gp);
to the Paint event and you'll see it: The fonts have quite a different size.
That is because when adding text to a GraphicsPath it is using a different scale (called 'emSize') than Graphics.DrawString does, which uses 'Point'.
To adapt you can use this:
float fontsize = 20.0f;
using (Graphics g = panel1.CreateGraphics()) fontsize *= g.DpiY / 72f;
Now you can build the GraphicsPath, best with the correct coordinates..:
gp.AddString("TEXT", new FontFamily("Arial"), 0, fontsize,
new Point(300, 100), StringFormat.GenericDefault);
Related
Trying to draw a shape over existing panels for a good while, but by now out of ideas. Could somebody help me out, please? It ends up always behind the panels (and pictureBox /the grey one/). I tried 3 different ways, whithout success. this is my code:
namespace DrawingOnFront
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel11_MouseClick(object sender, MouseEventArgs e)
{
DrawIt(90, 70);
}
private void DrawIt(int x, int y)
{
Rectangle Circle = new Rectangle(x,y,40,40);
SolidBrush Red = new SolidBrush(Color.Red);
Graphics g = this.CreateGraphics();
g.FillEllipse(Red, Circle);
/*
Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics g = Graphics.FromImage(bmp);
int width = pictureBox1.Width /4;
int height = pictureBox1.Height /2;
int diameter = Math.Min(width, height);
g.FillEllipse(Red, x, y, width, height);
pictureBox1.Image = bmp;
*/
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (Graphics g = e.Graphics)
{
Rectangle Circle = ClientRectangle;
Circle.Location = new Point(100, 60);
Circle.Size = new Size(40, 40);
using (SolidBrush Green = new SolidBrush(Color.Green))
{
g.FillEllipse(Green, Circle);
}
}
}
}
}
Sorry for this basic lama question, probably for most of you it is very easy, I am still learning it. Thanks a lot in advance.
My comments above apply. Here is an example of how to draw onto each control and the form separately:
We best have a common drawing routine that we can call from the Paint event of each participating element, in our case a Panel, a PictureBox and the Form.
The trick is for all nested elements to draw the circle shifted by their own location. To do so we pass these things into the drawing routine:
a valid Graphics object. We get it from the Paint events.
and a reference to the control; we use it to offset the drawing on each control (except the form) with Graphics.TranslateTransform..:
Result:
As you can see it looks as if we painted one circle over all elements but actually we drew three circles, each onto one element..:
private void canvasForm_Paint(object sender, PaintEventArgs e)
{
draw(sender as Control, e.Graphics);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
draw(sender as Control, e.Graphics);
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
draw(sender as Control, e.Graphics);
}
private void draw(Control ctl, Graphics g)
{
Rectangle r = new Rectangle(200, 100, 75, 75);
if (ctl != canvasForm) g.TranslateTransform(-ctl.Left, -ctl.Top);
g.FillEllipse(Brushes.Green, r);
g.ResetTransform();
}
Note that the same result could be created with three calls, one FillRectangle, one DrawImage and one FillEllipse :-)
i have to ZOOM-IN & ZOOM-OUT specific portion of 2D-graphics like (line, Rectangle, circle) which i have drawn on winform.
I am not used any picture box, panel.
I crated simple program to draw circle & on button click try to zoom
but it showing error "parameter is not valid"
in method Drawing() # Line- DeviceContexct.Transform = mainViewTransform;
public Graphics DeviceContexct;
public Matrix mainViewTransform = new Matrix();
private void ScalingCircle_Paint( object sender, PaintEventArgs e )
{
Pen myPen = new Pen(Color.Blue, 1);
e.Graphics.DrawRectangle(myPen, 50, 50, 100, 100);
mainViewTransform.Scale(3, 2);
DeviceContexct = e.Graphics;
}
private void Drawing(Graphics gr)
{
Pen myPen2 = new Pen(Color.Red, 1);
DeviceContexct.Transform = mainViewTransform;
DeviceContexct.DrawRectangle(myPen2, 50, 50, 100, 100);
}
private void button1_Click( object sender, EventArgs e )
{
Drawing(DeviceContexct);
}
I prefer to draw into Bitmaps with System.Drawing.Graphics object.
Then you can use your graphics object with "go.DrawImage(...)" to draw the bitmap directly into your winforms and actually give it a scale.
https://msdn.microsoft.com/en-us//library/ms142040(v=vs.110).aspx
I got the solution, thanks for your help.
I only need to call refresh/invalidate etc on button click.
public partial class ScalingCircle : Form
{
public Graphics DeviceContexct;
// current transformation matrix of main view (offset & scaling)
public Matrix mainViewTransform = new Matrix();
public int scale = 1;
public ScalingCircle()
{
InitializeComponent();
DeviceContexct = Graphics.FromHwnd(this.Handle);
DeviceContexct = this.CreateGraphics();
}
public void ScalingCircle_Paint(object sender, PaintEventArgs e)
{
DeviceContexct = e.Graphics;
DeviceContexct.PageUnit = GraphicsUnit.Pixel;
DeviceContexct.Transform = mainViewTransform;
ScalingCircle1(scale);
}
private void ScalingCircle1(int x )
{
Pen myPen2 = new Pen(Color.Black, 1);
DeviceContexct.Transform = mainViewTransform;
Rectangle myRectangle = new Rectangle(50, 50, 100 * x, 100 * x);
DeviceContexct.FillRectangle(new SolidBrush(Color.BurlyWood), myRectangle);
}
private void ScalingCircle_Load( object sender, EventArgs e )
{
this.ResizeRedraw = true;
}
private void button1_Click( object sender, EventArgs e )
{
scale += 5;
this.Refresh();
}
private void button2_Click( object sender, EventArgs e )
{
if (scale > 1)
{
scale -= 5;
this.Refresh();
}
}
}
You can use transformations for that. The graphics object you use for painting things has a Transformation property of type System.Drawing.Drawing2D.Matrix.
Graphics also has the ScaleTransform method.
I haven't used it myself, but that is how microsofts Chart does it.
https://msdn.microsoft.com/de-de/library/system.drawing.drawing2d.matrix(v=vs.110).aspx
https://msdn.microsoft.com/de-de/library/system.drawing.graphics.scaletransform(v=vs.110).aspx
I am adding one panel to another panel it works but circle which is in inspanel not shown. how can i solved this.
I am using below code. It works but not show circle
public static int xTemp = 0;
public static int yTemp = 0;
private void button1_Click(object sender, EventArgs e)
{
Panel insPanel = new Panel();
Random xRandom = new Random();
xTemp= xRandom.Next(20,100);
Random yRandom = new Random();
yTemp = yRandom.Next(20, 100);
insPanel.Location = new Point(xTemp, yTemp);
insPanel.Width=40;
insPanel.Height = 40;
insPanel.Visible = true;
insPanel.BorderStyle = BorderStyle.FixedSingle;
insPanel.Paint += new PaintEventHandler(insPanel_Paint);
panel1.Controls.Add(insPanel);
}
void insPanel_Paint(object sender, PaintEventArgs e)
{
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics =this.CreateGraphics();
formGraphics.FillEllipse(myBrush, new Rectangle(xTemp,yTemp, 10, 10));
myBrush.Dispose();
formGraphics.Dispose();
}
Main issue: you're trying to draw your circle at wrong coordinates.
xTemp and yTemp are coordinates of insPanel relative to panel1. But when you drawing your circle, you should use coordinates relative to panel you're drawing at - insPanel.
Another issue: there is no need to create and dispose graphics each time you're drawing something on your panel. You can use e.Graphics from Paint eventhandler arguments.
Based on above, your code could look like:
void insPanel_Paint(object sender, PaintEventArgs e)
{
using (var myBrush = new SolidBrush(Color.Red))
{
e.Graphics.FillEllipse(myBrush, new Rectangle(0, 0, 10, 10));
}
}
Also note - since paint event can occur very frequently, it could be a good idea not to create and dispose brush every time, but use brush cached in your class private field.
Use e.Graphics instead of this.CreateGraphics:
System.Drawing.Graphics formGraphics = e.Graphics;
One more issue is you're getting coordinates in range of 20 - 100 (xRandom.Next(20,100)) and your panel dimensions are just 40, 40.
I use the below code to set a gradient to a button in a windows form. It works but it's Text is not showing. What should I do to fix it?
Thank you.
private void Form1_Load(object sender, EventArgs e)
{
button2.Paint += new PaintEventHandler(this.Button2_Paint);
}
private void Button2_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(PointF.Empty, new PointF(button2.Width, button2.Height), Color.Pink, Color.Red), new RectangleF(PointF.Empty, button2.Size));
}
It's because you never actually drawing that text. Currently you only filling button's client rectangle with gradient, but there is no any text within. To show the string with button's text you need to add some more lines to Paint method:
private void Button2_Paint(object sender, PaintEventArgs e)
{
Button btn= (Button)sender;
Graphics g = e.Graphics;
g.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(PointF.Empty, new PointF(button2.Width, button2.Height), Color.Pink, Color.Red), new RectangleF(PointF.Empty, button2.Size));
SizeF size = g.MeasureString(btn.Text, btn.Font);
PointF topLeft = new PointF(btn.Width / 2 - size.Width / 2, btn.Height / 2 - size.Height / 2);
g.DrawString(btn.Text, btn.Font, Brushes.Black, topLeft);
}
Here Graphics.MeasureString gives you the width and height of a button's Text property, these values are used to position text right in the middle of a button. And Graphics.DrawString just draws the string with supplied color, font and position.
I found an article that does exactly what I need. It draws multiple colors on the same line on a text box. But the problem is that it was written in VB.NET and I'm writing my program in C#. Any good soul can convert this to C# if it is possible and if it isn't can you give me other options? Thanks.
This is the article: http://www.vbrad.com/article.aspx?id=34.
here is the conversion of what you posted Nicolas
if you need to change / get anything else working you will need to test it on your end..
Happy coding
private void MeasureItemHandler(object sender, MeasureItemEventArgs e)
{
Graphics g = Graphics.FromHwnd(lstColor.Handle);
StringFormat sf = new StringFormat(StringFormat.GenericTypographic);
SizeF size = default(SizeF);
float height = 0;
Font oFont = new Font("Arial", 10);
//measure the height of what you are about to draw
//and let the listbox know this
size = g.MeasureString(data(e.Index), oFont, 500, sf);
height = size.Height + 5;
e.ItemHeight = height;
}
private void DrawItemHandler(object sender, DrawItemEventArgs e)
{
Graphics g = Graphics.FromHwnd(lstColor.Handle);
StringFormat sf = new StringFormat(StringFormat.GenericTypographic);
SizeF size = default(SizeF);
float width = 0;
Font oFont = new Font("Arial", 10);
//get the width of the string you are about to write
//this info is needed so that we can offset the next
//string that will be drawn in a different color.
size = g.MeasureString(data(e.Index), oFont, 500, sf);
width = size.Width + 16;
//prepare the list for drawing
e.DrawBackground();
e.DrawFocusRectangle();
//draw the first string in a certain color
e.Graphics.DrawString(data(e.Index), oFont, new SolidBrush(color(e.Index)), e.Bounds.X, e.Bounds.Y);
//draw the second string in a different color
e.Graphics.DrawString(data(data.Length - 1 - e.Index), oFont, new SolidBrush(color(color.Length - 1 - e.Index)), width, e.Bounds.Y);
}
First of all, they aren't using a Textbox in this article, they are using a Listbox but what follows is a conversion of the code from VB.Net to C# like you asked. It needs tidied up a bit but it does the job.
Just create a new Windows Form, place a Listbox called lstColor onto this form, change the DrawMode property to OwnerDrawFixed inside the properties window, then add event handlers for DrawItem and MeasureItem (you can add event handlers by clicking on the lightning bolt in the Properties window, and double clicking the whitespace beside these two words in the list).
In the DrawItem event handler, add the following:
private void lstColor_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
var size = g.MeasureString(data[e.Index], oFont, 500, sf);
var width = size.Width + 16;
e.DrawBackground();
e.DrawFocusRectangle();
e.Graphics.DrawString(data[e.Index], oFont, new SolidBrush(color[e.Index]), e.Bounds.X, e.Bounds.Y);
e.Graphics.DrawString(data[data.Length - 1 - e.Index], oFont, new SolidBrush(color[color.Length - 1 - e.Index]), width, e.Bounds.Y);
}
In the MeasureItem event handler, add this:
private void lstColor_MeasureItem(object sender, MeasureItemEventArgs e)
{
var size = g.MeasureString(data[e.Index], oFont, 500, sf);
var height = size.Height;
e.ItemHeight = Convert.ToInt32(height);
}
Add five private fields outside the scope of any methods but inside your Form1 (or whatever you've called your form) class like so:
private string[] data;
private Color[] color;
private Font oFont;
private Graphics g;
private StringFormat sf;
Put the following three lines inside your Form1_Load event:
private void Form1_Load(object sender, EventArgs e)
{
oFont = new Font("Arial", 10);
data = new string[] { "This is Red", "This is Blue", "This is Green", "This is Yellow", "This is Black", "This is Aqua", "This is Brown", "This is Cyan", "This is Gray", "This is Pink" };
color = new Color[] {Color.Red, Color.Blue, Color.Green, Color.Yellow, Color.Black, Color.Aqua, Color.Brown, Color.Cyan, Color.Gray,Color.Pink};
lstColor.DataSource = data;
g = Graphics.FromHwnd(lstColor.Handle);
sf = new StringFormat(StringFormat.GenericTypographic);
}
And you are all set.
Hope this helps
Check out http://converter.telerik.com/ It converts code from VB.NET to C# and C# to VB.NET. It wont work on complex code, but could prove useful to you.