IT정보공유/C#

c# 이미지 해상도에 따라 자동으로 폰트 크기 조절 MeasureString

알지오™ 2021. 2. 17.

이미지위에 글자를 출력하려고 하는데, Graphics.DrawString() 함수로 글자를 출력하면 이미지파일 해상도에 따라서 글자크기가 작게 나오거나, 크게나오거나 정확한 글자를 출력하기가 어려웠습니다. 그래서 해상도에 상관없이 항상 일정한 비율로 글자크기가 출력되도록 하는 방법을 알아보도록 하겠습니다.

 

글자 크기 측정 함수 MeasureString()

Graphics 클래스의 정의되어 있는 MeasureString 함수는 문자열의 가로폭, 세로폭을 측정할 수 있습니다.

 

public SizeF MeasureString(string text, Font font);

 

아래의 화면 처럼 이미지 해상도에 비례하는 폰트 크기로 정중앙에 글자를 출력하는 샘플소스코드 입니다.
참고로 텍스트 출력시 사용하는 함수는 Graphics.DrawString()  이고, 함수 원형은 다음과 같습니다.

 

public void DrawString(string s, Font font, Brush brush, PointF point);

 

이미지 해상도에 따라 자동으로 폰트 크기 조절하는 프로그램
이미지 해상도에 따라 자동으로 폰트 크기 조절하는 프로그램

 

//

public Image picDrawTextCenter(Image img, string message, Color textColor)
        {
            try
            {

                float iX;
                float iY;
                Single Faktor, FaktorX, FaktorY;
                SizeF sz = new SizeF();

               
                using (Graphics grp = Graphics.FromImage(img))
                {
                    grp.CompositingQuality = CompositingQuality.GammaCorrected;

                    Font font1 = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);
                    sz = grp.MeasureString(message, font1);

                    FaktorX = (img.Width) / sz.Width;
                    FaktorY = (img.Height) / sz.Height;

                    if (FaktorX > FaktorY)
                        Faktor = FaktorY;
                    else
                        Faktor = FaktorX;

                    if (Faktor > 0)
                    {
                        font1 = new Font(font1.Name, font1.SizeInPoints * (Faktor));
                    }
                    else
                    {
                        font1 = new Font(font1.Name, font1.SizeInPoints * (0.1f));
                    }

                    sz = grp.MeasureString(message, font1);

                    iX = img.Width /2 - (sz.Width / 2);
                    iY = img.Height / 2 - (sz.Height / 2);

                    Brush brush = new SolidBrush(Color.FromArgb(128, textColor.R, textColor.G, textColor.B));
                    PointF pointF1 = new PointF(iX, iY);
                    grp.DrawString(message, font1, brush, pointF1);
                }

                return img;

            }
            catch (Exception exc)
            {
                
            }
            return img;
        }

//

 

글자 출력시에는 반투명으로 출력되기 때문에 이 부분도 참고해 보시기 바랍니다.

이 함수를 사용하게 되면 항상 일정한 크기로 이미지 해상도에 비례하는 글자크기로 문자열이 꽉 차서 출력됩니다.

 

글자
글자 수에 상관없이 화면에 꽉 차게 글자를 출력해 준다.

 

샘플 코드 관련 주의 사항

폰트 생성시 4번째 파라미터인 GraphicsUnit 은 Point로 하셔야합니다. Pixel로 할 경우 특정 해상도에서 글자크기가 엉뚱하게 출력됩니다.

댓글

💲 추천 글