훈스닷넷에 PictureBox위에 1cm 간격으로 눈금을 그리고 싶어하는 질문이 있어서

 

데모 프로젝트를 작성해보았습니다.

 

 

 

코드는 아래와 같습니다.

 

 

public partial class Form1 : Form

{

    /// <summary>

    /// 1pixel에 해당하는 센치

    /// </summary>

    const float OnePixelCentimetre = 37.79f;

    /// <summary>

    /// 수직라인 길이

    /// </summary>

    const int VerticalLineHeight = 50;

    /// <summary>

    /// 그리드 라인 색상

    /// </summary>

    readonly Pen gridLineColor;

 

    public Form1()

    {

        InitializeComponent();

        this.pictureBox1.Image = Image.FromFile("./Chrysanthemum.jpg");

 

        this.pictureBox1.Paint += PictureBox1_PaintEventHandler;

        this.SizeChanged += Form1_SizeChangedEventHandler;

        this.gridLineColor = Pens.Yellow;

    }

 

    /// <summary>

    /// 폼의 사이즈 변경 이벤트 처리기

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    private void Form1_SizeChangedEventHandler(object sender, EventArgs e)

    {

        this.pictureBox1.Invalidate();

    }

 

    /// <summary>

    /// PictureBox Paint 이벤트 처리기

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    private void PictureBox1_PaintEventHandler(object sender, PaintEventArgs e)

    {

        PictureBox pb = (PictureBox)sender;

        Graphics g = e.Graphics;

 

        //Picturebox의 중앙 위치

        float centerYPosition = pb.Height / 2.0f;

 

        //수평 라인 그리기

        g.DrawLine(gridLineColor, 0f, centerYPosition, pb.Width, centerYPosition);

 

        //현재 Picturbox에서 1cm 개수

        double cmStep = pb.Width / OnePixelCentimetre;

 

        //세로 라인의 절반

        int verticalLineHeightHalf = VerticalLineHeight / 2;

 

        //수직 라인 그리기

        for (float i = 0; i < pb.Width; i += OnePixelCentimetre)

        {

            PointF beginPoint = new PointF(i, centerYPosition - verticalLineHeightHalf);

            PointF endPoint = new PointF(i, centerYPosition + verticalLineHeightHalf);

            g.DrawLine(gridLineColor, beginPoint, endPoint);

        }

    }

}

 

 

 

프로젝트(vs2015 작성) : HowToDrawOnPicturebox.zip

 

+ Recent posts