2012-07-12 4 views
1

사용자 지정 컨트롤에서 오른쪽 맞춤 텍스트를 그려려고하지만 어떤 이유로 내 대상 가로 위치에 맞지 않아 문자열 사이에 차이가있는 것 같습니다.사용자 정의 문자열을 그릴 때 내 텍스트가 올바르게 정렬되지 않는 이유는 무엇입니까?

나는 그것이 나의 목표 수평 위치와 정확하게 일치하지 않는다는 사실로 살 수 있지만, 문자열 간의 차이는 시각적으로 끔찍하다.

모든 포인터?

enter image description here

분리 된 코드 :

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

namespace RightAlignTest { 
    class RightControlTest : UserControl { 
     public RightControlTest() { 
      this.SetStyle(ControlStyles.UserPaint, true); 
      this.SetStyle(ControlStyles.ResizeRedraw, true); 
     } 

     public static void DrawString(Graphics g, string s, Font f, RectangleF r, Color c) { 
      float locx = r.Left; 
      float locy = r.Top; 
      SizeF txts = g.MeasureString(s, f); 
      locx = (locx + r.Width - txts.Width); 
      g.DrawString(s, f, new SolidBrush(c), locx, locy); 
     } 

     protected override void OnPaint(PaintEventArgs e) { 
      base.OnPaint(e); 
      int rightTarget = Width - 20; 
      Font f = new Font("Arial Unicode MS", 13f, FontStyle.Regular); 
      int i = 0; 
      string[] strings = { "Current Limit 1:", "Current Limit 2:", "Temperature Center 1:", "Temperature Center 2:" }; 
      foreach (var s in strings) { 
       Rectangle r1 = new Rectangle(0, 30 * i++, rightTarget, Height); 
       DrawString(e.Graphics, s, f, r1, Color.Black); 
      } 
      e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Blue)), rightTarget, 0, rightTarget, Height); 
     } 
    } 
    public partial class Form1 : Form { 
     public Form1() { 
      RightControlTest t = new RightControlTest(); 
      t.Dock = DockStyle.Fill; 
      Controls.Add(t); 
     } 
    } 
} 

답변

2

이 작동하는지보십시오 :

public static void DrawString(
    Graphics g, string s, Font f, 
    RectangleF r, Color c) 
{ 
    StringFormat stringFormat = new StringFormat(); 
    stringFormat.Alignment = StringAlignment.Far; 
    stringFormat.LineAlignment = StringAlignment.Center; // Not necessary here 
    g.DrawString(s, f, new SolidBrush(c), r, stringFormat); 
} 

http://msdn.microsoft.com/en-us/library/332kzs7c.aspx에서

+0

컴파일러 오류를'촬영 StringFormat 예를 사용하여 'System.Drawing.StringAlignment '에는'Right '에 대한 정의가 없습니다. – Stormenet

+0

StringAlignment.Far이 (가) –

+0

LineAlignment가 필요하지 않습니다. –

관련 문제