Draw string along a circle 2 : Draw String « 2D « C# / CSharp Tutorial






Draw string along a circle 2
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class DrawStringAlignACircle : System.Windows.Forms.Form
{
  public DrawStringAlignACircle()
  {
    InitializeComponent();
    BackColor = SystemColors.Window;
    ForeColor = SystemColors.WindowText;
  }

  protected override void OnPaint ( PaintEventArgs e )
  {
    Graphics g = e.Graphics;
    SetScale(g);
    DrawFace(g);
    base.OnPaint(e);
  }
  private void InitializeComponent()
  {
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(292, 266);

  }

  [STAThread]
  static void Main() 
  {
    Application.Run(new DrawStringAlignACircle());
  }

  private void SetScale(Graphics g)
  {
    g.TranslateTransform(Width/2, Height/2);

    float inches = Math.Min(Width / g.DpiX, Height / g.DpiX);

    g.ScaleTransform(inches * g.DpiX / 2000, inches * g.DpiY / 2000);
  }

  private void DrawFace(Graphics g)
  {
    Brush brush = new SolidBrush(ForeColor);
    Font font = new Font("Arial", 40);
  
    float x, y;

    const int numHours = 12;
    const int deg = 360 / numHours;
    const int FaceRadius = 450;
    
    for (int i = 1; i <= numHours; i++)
    {
      SizeF stringSize = 
        g.MeasureString(i.ToString(),font);
        
      x = GetCos(i*deg + 90) * FaceRadius;
      x += stringSize.Width / 2;
      y = GetSin(i*deg + 90) * FaceRadius;
      y += stringSize.Height / 2;

      g.DrawString(i.ToString(), font, brush, -x, -y);
    
    }
    brush.Dispose();
    font.Dispose();
  }  

  private static float GetSin(float degAngle)
  {
    return (float) Math.Sin(Math.PI * degAngle / 180f);
  }

  private static float GetCos(float degAngle)
  {
    return (float) Math.Cos(Math.PI * degAngle / 180f);
  }

}








27.12.Draw String
27.12.1.A rectangle with some textA rectangle with some text
27.12.2.Draw string along a circleDraw string along a circle
27.12.3.Draw string along a circle 2Draw string along a circle 2
27.12.4.Draw string with HatchStyle