Posts Tagged: Graphics


7
Jul 09

DoUNo: When to use StringFormatFlags.DirectionRightToLeft and StringAlignment.Far

Recently I had a trouble displaying some values in a custom painted ListViewControl. I had to display some numbers right aligned. But I mistook this alignment with direction of the string, leading me to write the code as,

theArgs.Graphics.DrawString("100",
FONT_ISOVALUE_VALUE, Brushes.Black,
new Point(theArgs.Bounds.X + LOCATION_X_OFFSET, theArgs.Bounds.Y + LOCATION_Y_OFFSET),
new StringFormat(StringFormatFlags.DirectionRightToLeft));

This was working properly for positive values, but for negative values, the – sign comes after the number. i.e., instead of -100, it was displayed as 100-, thats when I understood the difference between RightToLeft text and right aligned texts. So replacing the above snippet with the following snippet does the work.

StringFormat aStringFormat = new StringFormat();
aStringFormat.Alignment = StringAlignment.Far;
theArgs.Graphics.DrawString("-100",
FONT_ISOVALUE_VALUE, Brushes.Black,
new Point(theArgs.Bounds.X + LOCATION_X_OFFSET, theArgs.Bounds.Y + LOCATION_Y_OFFSET),
aStringFormat );

So alignment is different and direction of text is different. Use StringFormat.Alignment for alignment and StringFormatFlags for direction


2
Feb 09

Drawing lines in C#

Lines can be drawn in many ways in C#. Here we will try to draw a line using the Graphics.DrawLine method.

Graphics.DrawLine takes a pen to draw the line. So it boils down to the pen to get various styles of lines.

Lets try a simple solid one.

Create a pen. Here again to create a pen we need a Brush. Lets keep it really a simple pen. So we create a simple SolidBrush now.

Brush aSolidBrush = new SolidBrush(Color.Black);  //Creates a black solid brush for the pen  

Simple isn’t it ??

Pen aSolidPen = new Pen(aSolidBrush);  //Assigns the SolidBrush to the Pen  

Graphics.DrawLine(aSolidPen, new Point(0, 10), new Point(100, 10));  //Draws a solid horizontal line  

Lets play with the different styles of lines now.

Different styles of lines, as said earlier depends on different styles of Pens (which depends on Brushes). So how do we change the style of a pen ??? Answers are many,

Using a Line Pattern

This denotes whether the line is a dotted one or dashed one or dot dashed one or etc. Use the DashStyle property of the pen to change the patter of the line.

aSolidPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;  //Gives you a dashed line  

There are a few more styles available in the System.Drawing.Drawing2D.DashStyle enum  

aSolidPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;  //Gives you a dotted line  

Using a DashPattern  

This is similar to the first one but here you can control the space and width of the each dot / dash in the line. To manipulate them use the DashPattern property of the pen.

aBorderPen.DashPattern = new float []{ 1, 1 };  //Gives you a dotted line (rather a dashed line with width 1px) and the space bettwen the consecutive dot is 1px


aBorderPen.DashPattern = new float []{ 2, 3 };  //Gives you a dashed line with 2px width for the dashes and 3px width between the dashes  

Using a GradientBrush  

You can even play with the brushes to get different style lines (as Pens are inturn dependent of Brushes). Use a LinearGradientBrush to get gradient lines.  

Brush aGradientBrush = new LinearGradientBrush(new Point(0, 0), new Point(20, 0), Color.Black, Color.Gray);  //Gives you a gradinet brush with black and gray colors. This will be a vertical gradient as the second point changes in the x axis  

Pen aGradientPen = new Pen(aGradientBrush);  //Assigns the GradientBrush to the Pen  

Graphics.DrawLine(aGradientPen, new Point(0, 10), new Point(100, 10));  //Draws a horizontal line which is Gradiently Filled

These are some of the ways to draw weird lines in C#. If you have your own style, draw it here.


12
Dec 08

Analog Clock in C#

Recently when I was working with my Quick Calendar (will talk about that later), I was thinking about an analog clock in C#. I didn’t wanna google for simple stuffs and so started off with it. This was really a quick clock thou’. Here is how I did it.  

Before we can proceed, let me tell you how (rather the logic) behind the analog clock. We will draw the needles from the center of the clock to circumference of the clock. So we need to know,

  1. Length of the needle (will be a constant in our case)
  2. Origin point, where the needle is fixed (will be the center of a picturebox in our case)
  3. Point on the circumference till which the line needs to be drawn

Of all the above the only thing that needs to be found is the point on the circumference of the clock at any given second. Anyways, to find it we know the angle (Hint: At 15th second the needle will be at 90deg and at 30th minute the needle will be at 180deg). So the angle is the second multiplied by 6 (as at 15 seconds, angle is 15 * 6)

angle = second * 6

Now that we have the angle, we can find the co-ordinate on the circumference of the circle in a very simple way. Following the concepts of 5th grade Maths. Construct a right angled triangle as shown. Since we know the value of angle (theta), we can find x and y using the formulae,

sin theta = opposite side / hypotaneous and cos theta = adjacent side / hypotaneous

=> x = sin theta * hyp and y = cos theta * hyp

Great. We know the points on the circumference also. Thats it, our second hand is ready now. Minute hand is also similar to the second hand, but for the hour hand, the angle will be second * 30 ( 30 times 3′o clock is 90degrees). Lets see the programitical implementation of this.

  • Put a timer in to your window application with the interval 1000 (1000 millisecond = 1 second)
  • In the tick event of the timer, do the following

                this.Refresh();  //Will clear the previously drawn lines
                int aHour = DateTime.Now.Hour;  //Calculates the hour
                int aMinutes = DateTime.Now.Minute;  //Minutes
                int aSecond = DateTime.Now.Second;  //Seconds


                Graphics aGraphics = pictureBox1.CreateGraphics();  //Get the graphics object of the picturebox so that we can draw the needles (hands)
                aGraphics.FillRectangle(Brushes.DarkGray, new Rectangle(0, 0, pictureBox1.Size.Width, pictureBox1.Size.Height));  //Draws a black rectangle as the background for our clock
                
                PointF aSecondsPoint = FindXAndY(-(aSecond * 6));  //Will find the co-ordinate points at the current instance  
                aGraphics.DrawLine(Pens.LightBlue, pictureBox1.Width / 2, pictureBox1.Height / 2, aSecondsPoint.X, aSecondsPoint.Y);  //Draws the seconds hand
                aGraphics.DrawString(aSecond.ToString(), aSecondsFont, Brushes.Blue, FindXAndY(-(aSecond * 6)));  //A small string that comes with the hand


                PointF aMinutesPoint = FindXAndY(-(aMinutes * 6));  //Similar to the seconds hand 
               aGraphics.DrawLine(Pens.LightGreen, pictureBox1.Width / 2, pictureBox1.Height / 2, aMinutesPoint.X, aMinutesPoint.Y);
                aGraphics.DrawString(aMinutes.ToString(), aMinutesFont, Brushes.Green, FindXAndY(-(aMinutes * 6)));


                PointF aHoursPoint = FindXAndY(-(aHour * 30));  //Simular to the minutes hand, but multiplied by 30. Refer to the explanation section to know more about this
                aGraphics.DrawLine(aHoursPen, pictureBox1.Width / 2, pictureBox1.Height / 2, aHoursPoint.X, aHoursPoint.Y);
                aGraphics.DrawString(aHour.ToString(), aHoursFont, Brushes.OrangeRed, aHoursPoint.X, aHoursPoint.Y);
  • Here is the definition for the FindXAndY method,

            private PointF FindXAndY(int theAngle)
            {
                float x2 = pictureBox1.Width / 2 - 75 * (float)Math.Sin(Math.PI / 180 * theAngle);  //Converting the angle to radians and finding the X position
                float y2 = pictureBox1.Width / 2 - 75 * (float)Math.Cos(Math.PI / 180 * theAngle);  //Converting the angle to radians and finding the Y position
                PointF aPoint = new PointF(x2, y2);
                return aPoint;
            }

Hope you have got something really useful today. If you have some other better solutions, put it over here.


31
Oct 08

Rubber band selection rectangle in C#

Rubber band selection rectangle -- This is how it looks like finally

You might have selected a couple of icons from your desktop by dragging the left mouse button and my drawing a rectangle over the icons. Such rectangles are called Rubber band selection rectangles. A rubber band selection is a selection rectangle that will track down the mouse pointer when the left mouse button is held.

In this artilce, we will try to draw those kina rectangles in C#. The article covers only the drawing part.

Lets get started.

Here are the terms used in the explanation,
I will be helping you draw the rectangle using four connected lines.

  • Origin point (O) to denote the place from which the user has started to draw the rectangle
  • Intermediate point (I) to refer to the incremental points over which the user has moved his mouse pointer
  • Nearer – close to the mouse pointer
  • Farther – distant from the mouse pointer
  • Ox, Oy referes to the Origin’s X and Origin’s Y

Continue reading →


15
Oct 08

Glossy buttons in c#

Is there any way to create glossy, eye candy buttons in c# ?? Before starting off, we need to know what makes a thing glossy. There are two factors,

  • Color selection
  • Linear gradient fill over the control

Ok. Now lets see the implementation. For colors, we have Color class, but for Lineargradient ?? Yeah, we do have a LinearGradientBrush in c#.

Note: The task of making a button glossy will be acheived in the following order,

  • Drawing the border
  • Filling the lower rectangle with a solid color
  • Filling the upper rectangle with a linear gradient
  1. Include a button to the project (myGlossyButton)
  2. Change the FlatStyle of the myGlossyButton to Flat

    myGlossyButton.FlatStyle = FlatStyle.Flat;
  3. Handle the paint event of this button. Lets name the handler method as GlossyPainter
  4. In the GlossyPainter, first we need to give our button a border [task:1]. Say White border.

    e.Graphics.DrawRectangle(Pens.White, new Rectangle(0, 0, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1));  //1 is subtracted from the size to make the border completely visible
  5. Next up, we need to fill the rectangle with some base color [task:2]. This time, we will fill the bottom half with some solid color and the upper half with some gradient color.

    SolidBrush aBaseSolidbrush = new SolidBrush(Color.FromArgb(150, Color.YellowGreen));  //FromArgb allows you to even specify the opacity of the colore.Graphics.FillRectangle(aBaseSolidBrush,  new Rectangle(2, (e.ClipRectangle.Height - 4) / 2, e.ClipRectangle.Width - 4, e.ClipRectangle.Height - 4));  //4 is subtracted just to leave a blank space between the border and the button     

  6. Filling the upper part of the button with the linear gradient color [task:3]

    LinearGradientBrush aLineargradientBrush = new LinearGradientBrush(new Rectangle(2, 2, e.ClipRectangle.Width - 4, (e.ClipRectangle.Height - 4) / 2), Color.FromArgb(255, Color.White), Color.FromArgb(100, aColor), 90);  //Specifying how big the linear gradient should be and in what direction the gradient should appear

    e.Graphics.FillRectangle(aLinearGradientBrush, new Rectangle(2, 2, e.ClipRectangle.Width - 4, (e.ClipRectangle.Height - 4) / 2));  //Filling the upperpart of the button
  7. Run the application, you should be seeing a glossy button

This is one of the ways to make a control look glossy. There are many ways to acheive this. If you know a really simple way share it with us.