문제

내가 사용하는.NETCF(윈도우 모바일) Graphics 클래스고 DrawString() 메서드를 렌더링하는 하나의 캐릭터 화면입니다.

문제할 수 없는 것 그것을 얻을 중심으로.무슨 상관 없이 나는 설정의 Y 좌표 위치에 문자열의 렌더링,그것은 항상 그것 보다는 더 낮고 텍스트 크기가 더 큰 Y 오프셋이 있습니다.

예를 들어,텍스트 크기는 12 일 오프셋은 4 지만,32 오프셋은 약 10.

내가 원하는 캐릭터가 수직으로의 대부분을 차지하며 그것은 사각형의 것에 그려진 및 중심으로 수평.여기에서의 내한 기본 코드입니다. this 참조하는 사용자가 제어되고 있는지 그려집니다.

Graphics g = this.CreateGraphics();

float padx = ((float)this.Size.Width) * (0.05F);
float pady = ((float)this.Size.Height) * (0.05F);

float width = ((float)this.Size.Width) - 2 * padx;
float height = ((float)this.Size.Height) - 2 * pady;

float emSize = height;

g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular),
            new SolidBrush(Color.Black), padx, pady);

그렇다,나는 거기에 레이블을 제어할 수 있는 대신 사용하고 설정의 중심지만,실제로 나는 할 필요가 이렇게 수동으로 함 Graphics 클래스입니다.

도움이 되었습니까?

해결책 3

조합을 통해의 제안 내가 가지고,그렇게 해서 찾아낸:

    private void DrawLetter()
    {
        Graphics g = this.CreateGraphics();

        float width = ((float)this.ClientRectangle.Width);
        float height = ((float)this.ClientRectangle.Width);

        float emSize = height;

        Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);

        font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);

        SizeF size = g.MeasureString(letter.ToString(), font);
        g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);

    }

    private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
    {
        // Compute actual size, shrink if needed
        while (true)
        {
            SizeF size = g.MeasureString(text, font);

            // It fits, back out
            if (size.Height <= proposedSize.Height &&
                 size.Width <= proposedSize.Width) { return font; }

            // Try a smaller font (90% of old size)
            Font oldFont = font;
            font = new Font(font.Name, (float)(font.Size * .9), font.Style);
            oldFont.Dispose();
        }
    }

지금까지,이는 완벽하게 작동합니다.

는 변경을 이동하는 것입 FindBestFitFont()호출에 레이아웃 논리를 강제로 적()이벤트에 그래서 나는 그 때마다 나는 그리합니다.그것은 단지 요구를 호출될 때 제어 크기를 변경할 수 있습니다.나는 그냥 그것을 포함하는 기능에 완전성을 위해 함께 설명합니다.

다른 팁

고 싶은 다른 추가로 투표를 StringFormat 개체입니다.이 사용할 수 있습니다 간단하게 지정한"센터,센터"텍스트와 그려집니다 중앙에는 직사각형 또는 포인트 제공

StringFormat format = new StringFormat();
format.LineAlignment = StringAlignment.Center;
format.Alignment = StringAlignment.Center;

그러나 하나의 문제이다.를 사용하면 센터에 대한 두 값이 다음 그것은 TextWrapping 다.아무 생각이 왜 이런 일이 일어나는,그것은 버그를 가진다.

맞게 텍스트를 사용하려면 다음을 사용합니다.

StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
e.Graphics.DrawString("My String", this.Font, Brushes.Black, ClientRectangle, sf);

참고해 주십시오 여기 텍스트를 정렬에 주어진 경계.이 샘플에서 이 ClientRectangle.

을 그릴 중심으로 텍스트:

TextRenderer.DrawText(g, "my text", Font, Bounds, ForeColor, BackColor, 
  TextFormatFlags.HorizontalCenter | 
  TextFormatFlags.VerticalCenter |
  TextFormatFlags.GlyphOverhangPadding);

을 결정하는 최적의 글꼴 크기의 영역을 채우기 위해 약간 더 어렵습니다.하나의 작업 soultion 내가 찾는 것은 시험과 오류가:시작으로 큰 글꼴,다음 반복적으로 측정한 문자열 및 수축 글꼴을 때까지 그것은 맞습니다.

Font FindBestFitFont(Graphics g, String text, Font font, 
  Size proposedSize, TextFormatFlags flags)
{ 
  // Compute actual size, shrink if needed
  while (true)
  {
    Size size = TextRenderer.MeasureText(g, text, font, proposedSize, flags);

    // It fits, back out
    if ( size.Height <= proposedSize.Height && 
         size.Width <= proposedSize.Width) { return font; }

    // Try a smaller font (90% of old size)
    Font oldFont = font;
    font = new Font(font.FontFamily, (float)(font.Size * .9)); 
    oldFont.Dispose();
  }
}

당신은 것으로 사용:

Font bestFitFont = FindBestFitFont(g, text, someBigFont, sizeToFitIn, flags);
// Then do your drawing using the bestFitFont
// Don't forget to dispose the font (if/when needed)

당신이 사용할 수 있습의 인스턴스 StringFormat 체에 전달된 DrawString 메서드를 중심으로 텍스트입니다.

그래픽입니다.졸라매는 끈 방법StringFormat 클래스.

여기에 몇 가지 코드입니다.이 있다고 가정에서 이렇게 하면 양식,또는 정렬.

Graphics g = this.CreateGraphics();
SizeF size = g.MeasureString("string to measure");

int nLeft = Convert.ToInt32((this.ClientRectangle.Width / 2) - (size.Width / 2));
int nTop = Convert.ToInt32((this.ClientRectangle.Height / 2) - (size.Height / 2));

귀하의 게시물에서,그 소리와 같은 ClientRectangle 일(로에서,당신은 그것을 사용하지 않)은 무엇을 주는 당신이 어려움이 있다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top