I need to draw a rectangle into a panel. I dont know the color in advance, I get the color during runtime, I dont know how to set the color not to a fixed value, and second - when i try to draw the rectangle, it does nothing at all. Here is my code that should draw the rectangle (infact it does in another project, but thats just in a plain form, not into a panel)
Graphics g;
g = CreateGraphics();
Pen p;
Rectangle r;
p = new Pen(Brushes.Blue);
r = new Rectangle(1, 1, 578, 38);
g.DrawRectangle(p, r);`
So I need to replace (Brushes.Blue) with a variable and I need to draw the rectangle in a panel on its coordinates set in this code..
Construct your Pen using the Pen(Color) constructor instead of the Pen(Brush) one. Then you can define your color once you know it.
You should perform drawing in the Paint event of the panel. This event occurs whenever windows decides it's time to repaint the panel, and the PaintEventArgs contain a Graphics object you can draw the rectangle on.
The Brush is an abstract class, but you can use the SolidBrush object to create a custom colored brush at runtime:
int red = 255;
int green = 0;
int blue = 0;
Brush myBrush = new SolidBrush(Color.FromArgb(red, green, blue));
Here you are:
private Color _color; // save the color somewhere
private bool iKnowDaColor = false; // this will be set to true when we know the color
public Form1() {
InitializeComponents();
// on invalidate we want to be able to draw the rectangle
panel1.Paint += new PaintEventHandler(panel_Paint);
}
void panel_Paint(object sender, PaintEventArgs e) {
// if we know the color paint the rectangle
if(iKnowDaColor) {
e.Graphics.DrawRectangle(new Pen(_color),
1, 1, 578, 38);
}
}
And when you know the color:
_color = ...
iKnowDaColor = true;
// causes the panel to invalidate and our painting procedure to be called
panel.Invalidate();
I haven't tested this but should give you the basic idea.
put the following code in the appropriate place :
Graphics g = panel1.CreateGraphics();
int redInt=255, blueInt=255, greenInt=255; //255 is example, give it what u know
Pen p = new Pen(Color.FromArgb(redInt,blueInt,greenInt));
Rectangle r = new Rectangle(1, 1, 578, 38);
g.DrawRectangle(p, r);
and if you wanted to draw the rectangle somewhere else, say the form, you could do g = this.CreateGraphics.
I think that the better way of doing that is to extend the Panel class and add some custom OnPaint event logic.
public class PanelRect : Panel
{
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (Graphics g = e.Graphics)
{
Rectangle rect = ClientRectangle;
rect.Location = new Point(20, 20); // specify rectangle relative position here (relative to parent container)
rect.Size = new Size(30, 30); // specify rectangle size here
using (Brush brush = new SolidBrush(Color.Aqua)) // specify color here and brush type here
{
g.FillRectangle(brush, rect);
}
}
}
}
P.S. This is not an advanced example, but might help you. You can move size, location and color etc to properties so you can easily change them from designer.
P.S. P.S. If you need a non-filled rectangle just use Pen object instead of Brush (you might also change the FillRectangle to something more suitable).
Related
i want to have outer glow text in a label for my winform application some thing like:
i searched for it in stackoverflow and I found this:
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
//Create a bitmap in a fixed ratio to the original drawing area.
Bitmap bm=new Bitmap(this.ClientSize.Width/5, this.ClientSize.Height/5);
//Create a GraphicsPath object.
GraphicsPath pth=new GraphicsPath();
//Add the string in the chosen style.
pth.AddString("Text Halo",new FontFamily("Verdana"),(int)FontStyle.Regular,100,new Point(20,20),StringFormat.GenericTypographic);
//Get the graphics object for the image.
Graphics g=Graphics.FromImage(bm);
//Create a matrix that shrinks the drawing output by the fixed ratio.
Matrix mx=new Matrix(1.0f/5,0,0,1.0f/5,-(1.0f/5),-(1.0f/5));
//Choose an appropriate smoothing mode for the halo.
g.SmoothingMode=SmoothingMode.AntiAlias;
//Transform the graphics object so that the same half may be used for both halo and text output.
g.Transform=mx;
//Using a suitable pen...
Pen p=new Pen(Color.Yellow,3);
//Draw around the outline of the path
g.DrawPath(p,pth);
//and then fill in for good measure.
g.FillPath(Brushes.Yellow,pth);
//We no longer need this graphics object
g.Dispose();
//this just shifts the effect a little bit so that the edge isn't cut off in the demonstration
e.Graphics.Transform=new Matrix(1,0,0,1,50,50);
//setup the smoothing mode for path drawing
e.Graphics.SmoothingMode=SmoothingMode.AntiAlias;
//and the interpolation mode for the expansion of the halo bitmap
e.Graphics.InterpolationMode=InterpolationMode.HighQualityBicubic;
//expand the halo making the edges nice and fuzzy.
e.Graphics.DrawImage(bm,ClientRectangle,0,0,bm.Width,bm.Height,GraphicsUnit.Pixel);
//Redraw the original text
e.Graphics.FillPath(Brushes.Black,pth);
//and you're done.
pth.Dispose();
}
but the PROBLEM IS I CAN NOT MOVE IT please help me i need it to be movable and I want to be able to change it's size. the code above, just adds it automatically to somewhere in my form but I want to move that.
thank you
A better approach is to create a custom control for this to use/add some relevant drawing properties. Mainly, the Font and color of the text, the size and color of the outline. Then, you can lay out the custom control in any container at any location and with any size.
Here's a simple example.
[DesignerCategory("Code")]
public class GlowTextLabel : Control
{
private Color outlineColor = SystemColors.Highlight;
private int outlineSize = 1;
public GlowTextLabel() : base()
{
SetStyle(ControlStyles.Selectable, false);
SetStyle(ControlStyles.OptimizedDoubleBuffer |
ControlStyles.ResizeRedraw |
ControlStyles.SupportsTransparentBackColor, true);
}
[DefaultValue(typeof(Color), "Highlight")]
public Color OutlineColor
{
get => outlineColor;
set
{
if (outlineColor != value)
{
outlineColor = value;
Invalidate();
}
}
}
[DefaultValue(1)]
public int OutlineSize
{
get => outlineSize;
set
{
if (outlineSize != value)
{
outlineSize = Math.Max(1, value);
Invalidate();
}
}
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
var w = Math.Max(8, ClientSize.Width / 5);
var h = Math.Max(8, ClientSize.Height / 5);
using (var bmp = new Bitmap(w, h))
using (var gp = new GraphicsPath())
using (var sf = new StringFormat(StringFormat.GenericTypographic))
{
sf.Alignment = sf.LineAlignment = StringAlignment.Center;
gp.AddString(Text,
Font.FontFamily, (int)Font.Style, GetEmFontSize(Font),
ClientRectangle, sf);
using (var g = Graphics.FromImage(bmp))
using (var m = new Matrix(1.0f / 5, 0, 0, 1.0f / 5, -(1.0f / 5), -(1.0f / 5)))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Transform = m;
using (var pn = new Pen(OutlineColor, OutlineSize))
{
g.DrawPath(pn, gp);
g.FillPath(pn.Brush, gp);
}
}
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Optional for wider blur...
// e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
e.Graphics.DrawImage(bmp,
ClientRectangle, 0, 0, bmp.Width, bmp.Height,
GraphicsUnit.Pixel);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using (var br = new SolidBrush(ForeColor))
e.Graphics.FillPath(br, gp);
}
}
}
private float GetEmFontSize(Font fnt) =>
fnt.SizeInPoints * (fnt.FontFamily.GetCellAscent(fnt.Style) +
fnt.FontFamily.GetCellDescent(fnt.Style)) / fnt.FontFamily.GetEmHeight(fnt.Style);
Rebuild, find the GlowTextLabel control on the ToolBox under your project's components group, drop an instance, try the Font, ForeColor, OutlineColor, and OutlineSize properties with different values.
Pen width 1.
Pen width 10.
Pen width 20.
I am trying to draw a circle within my form.
But it is strange to me I set form width and height to a fixed number, i do the same for the circle, but the circle figure goes outside the form.
private void Form3_Paint(object sender, PaintEventArgs e)
{
this.SuspendLayout();
gr = this.CreateGraphics();
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Brush fill_circ3 = Brushes.Blue;
Pen ellipse_pen = new Pen(Color.Blue);
ellipse_pen.Width = (float)2.0;
this.Width = this.Height = 400;
Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
gr.DrawEllipse(ellipse_pen, rect);
this.ResumeLayout();
}
The 3rd and 4th parameters of the Rectangle constructor defines the size in width and height of the circle.
See the circle I got
Why does the circle goes outside the form???! I have set form and circle sizes the same!!!
It's because you use the Window size, not the "client" size. Just replace your code by this:
gr.DrawEllipse(ellipse_pen, this.ClientRectangle);
The client area of a control is the bounds of the control, minus the
nonclient elements such as scroll bars, borders, title bars, and
menus.
I want to make a bitmap that has a linear opacity applied. (i.e. it is more opaque on the left side and get progressively less opaque as it approaches the right.)
Is this possible? I know its possible to have a constant opacity level.
I know its possible to have a constant opacity level
So don't make it constant, LinearGradientBrush has no trouble interpolating the alpha value. A simple demonstration of a form that has the BackgroundImage set:
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
var rc = new Rectangle(20, 20, this.ClientSize.Width - 40, 50);
using (var brush = new System.Drawing.Drawing2D.LinearGradientBrush(
rc,
Color.FromArgb(255, Color.BlueViolet),
Color.FromArgb(0, Color.BlueViolet),
0f)) {
e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
e.Graphics.FillRectangle(brush, rc);
}
}
Produced:
Put the BitMap into a PictureBox control. Then you will have to use the PictureBox's Paint event handler to do the fading. Something like
private void pictureBox_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(pictureBox.Image, 0, 0,
pictureBox.ClientRectangle, GraphicsUnit.Pixel);
Color left = Color.FromArgb(128, Color.Blue);
Color right = Color.FromArgb(128, Color.Red);
LinearGradientMode direction = LinearGradientMode.Horizontal;
LinearGradientBrush brush = new LinearGradientBrush(
pictureBox.ClientRectangle, left, right, direction);
e.Graphics.FillRectangle(brush, pictureBox.ClientRectangle);
}
This example fades the image overlay from blue to red. I am sure you can play with this to get what you want working.
I hope this helps.
I want to draw always visible cross over picturebox on winform. I know ho to use Graphics and it's method DrawLine. But problem is that, painted cross is hidden behind the picturebox. this textbox is continually refreshed and this cross should be always visible.
Do you have some solution for this?
Here is code:
Point picBoxLocation = pictureBox.Location;
Size picBoxSize = pictureBox.Size;
Pen myPen = new Pen(System.Drawing.Color.Red, 5);
Point left = new Point(picBoxLocation.X, picBoxSize.Height/2);
Point right = new Point(picBoxLocation.X+picBoxSize.Width, picBoxSize.Height / 2);
Point up = new Point((picBoxLocation.X + picBoxSize.Width) / 2, picBoxLocation.Y);
Point bottom = new Point((picBoxLocation.X + picBoxSize.Width) / 2, (picBoxLocation.Y+picBoxSize.Height)/2);
Graphics graphics = this.CreateGraphics();
graphics.DrawLine(myPen, left, right);
graphics.DrawLine(myPen, up, bottom);
Try to get Graphics object in OnPaint callback:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawLine(...);
}
I'm trying to draw a line that goes from middle top to bottom.
I know I have to use the Pen class to accomplish this.
private void RepaintPreview()
{
Pen blackPen = new Pen(Brushes.Black);
blackPen.Width = 1.0f;
blackPen.LineJoin = System.Drawing.Drawing2D.LineJoin.Bevel;
ptbTablePreview.Image.draw?
}
Basically, how can I draw this line on the image? Thank you.
I tried the following, and it works with me:
1- I set the image of the picturebox in design time
2- I handled the Paint event of the picturebox, and added the following code:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
using (Pen p = new Pen(Color.Black, 2))
{
e.Graphics.DrawLine(p, new Point(pictureBox1.Width / 2, 0), new Point(pictureBox1.Width / 2, pictureBox1.Height));
}
}