Friday, January 25, 2008

Ruler in C#.NET

Here i have posted Ruler user control

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace RulerTest
{
public partial class Ruler : UserControl
{
private int _width;
private int _height;

public int RulerWidth
{
get { return _width; }
set { _width = value; }
}
public int RulerHeight
{
get { return _height; }
set { _height = value; }
}

public Ruler()
{
InitializeComponent();
}


private void DrawRuler(Graphics g, int formWidth, int formHeight)
{
// Border
//g.DrawRectangle(Pens.Black, 0, 0, formWidth - 1, formHeight - 1);


// Width
//g.DrawString(formWidth + " pixels", Font, Brushes.Black, 10, (formHeight / 2) - (Font.Height / 2));

// Ticks
for (int i = 0; i < formWidth; i++)
{
if (i % 2 == 0)
{
int tickHeight;
if (i % 100 == 0)
{
tickHeight = 15;
DrawTickLabel(g, i.ToString(), i, formHeight, tickHeight);
DrawTick(g, i, formHeight, tickHeight);
}
else if (i % 10 == 0)
{
tickHeight = 10;
DrawTick(g, i, formHeight, tickHeight);
}
else
{
tickHeight = 5;
}


}
}
}

private static void DrawTick(Graphics g, int xPos, int formHeight, int tickHeight)
{

// Top
g.DrawLine(Pens.White, xPos + 50, 40, xPos + 50, -tickHeight + 40);

// Left
g.DrawLine(Pens.White, 40, xPos + 50, -tickHeight + 40, xPos + 50);

}


private void DrawTickLabel(Graphics g, string text, int xPos, int formHeight, int height)
{
// Top
g.DrawString(text, Font, Brushes.White, xPos + 45, -height + 20);

// Left
g.DrawString(text, Font, Brushes.White, -height+20, xPos+45);
}

private void Ruler_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;
int height = Width;
int width = Height;

DrawRuler(graphics, width, height);



}


}
}

No comments: