2014-01-22 5 views
0

다음 코드는 문자열을 가져 와서 메모리에있는 비트 맵에 추가 한 다음 BMP 파일로 저장합니다. 내가 가지고있는 코드는 다음과 같습니다.비트 맵 만들기 및 C# 파일 저장 비트 맵에 비어있는 텍스트 제공

string sFileData = "Hello World"; 
string sFileName = "Bitmap.bmp"; 

Bitmap oBitmap = new Bitmap(1,1); 
Font oFont = new Font("Arial", 11, FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); 
int iWidth = 0; 
int iHeight = 0; 

using (Graphics oGraphics = Graphics.FromImage(oBitmap)) 
{ 
    oGraphics.Clear(Color.White); 

    iWidth = (int)oGraphics.MeasureString(sFileData, oFont).Width; 
    iHeight = (int)oGraphics.MeasureString(sFileData, oFont).Height; 
    oBitmap = new Bitmap(oBitmap, new Size(iWidth, iHeight)); 

    oGraphics.DrawString(sFileData, oFont, new SolidBrush(System.Drawing.Color.Black), 0, 0); 

    oGraphics.Flush(); 

} 

oBitmap.Save(sFileName, System.Drawing.Imaging.ImageFormat.Bmp); 

나는 페인트의 BMP 파일을 볼 때 내가 가진 문제는, 비트 맵의 ​​크기가 배경이 흰색, 올바르게 정의되어 있지만 텍스트가 자신입니까?

내가 뭘 잘못하고 있니?

답변

6

Bitmap 개체를 만든 다음 Graphics 개체를 using 문에 바인딩합니다. 그런 다음 해당 Bitmap 개체를 파괴하고 원래 바인딩을 잃어 버리는 새 개체를 만듭니다. Bitmap을 한 번만 만들어보세요.

편집

나는 당신이 그리는 하나의 물건을 측정하는 두 가지 목적, 하나의 Graphics 객체를 사용하려고하고있는 것을 알 수있다. 이것은 나쁜 것은 아니지만 문제를 일으키는 것입니다. reading the threads in this post for an alternative way for measuring strings을 권하고 싶습니다. 저는 개인적으로 가장 좋아하는 helper class from this specific answer을 사용할 것입니다.

public static class GraphicsHelper { 
    public static SizeF MeasureString(string s, Font font) { 
     SizeF result; 
     using (var image = new Bitmap(1, 1)) { 
      using (var g = Graphics.FromImage(image)) { 
       result = g.MeasureString(s, font); 
      } 
     } 
    return result; 
    } 
} 

string sFileData = "Hello World"; 
string sFileName = "Bitmap.bmp"; 

Font oFont = new Font("Arial", 11, FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); 
var sz = GraphicsHelper.MeasureString(sFileData, oFont); 

var oBitmap = new Bitmap((int)sz.Width, (int)sz.Height); 

using (Graphics oGraphics = Graphics.FromImage(oBitmap)) { 
    oGraphics.Clear(Color.White); 
    oGraphics.DrawString(sFileData, oFont, new SolidBrush(System.Drawing.Color.Black), 0, 0); 
    oGraphics.Flush(); 

} 

oBitmap.Save(sFileName, System.Drawing.Imaging.ImageFormat.Bmp); 
+2

+1 문제가 발견되기 전에 +1하지만 정의되기 전에'oGraphics'를 사용하기 때문에 예제가 작동하지 않습니다 –

+0

아, 지금 업데이트 중입니다 ... –

0

중간에 비트 맵을 바꾼 것으로 보입니다. 다음과 같은 일을 할 것 : 다른 크기의 새 비트 맵을 만들 그래픽 비트 맵

  • 에 처리
  • 이 오기 비트 맵을 작성

    문제는 '당신이 즉 새 (두 번째) 비트 맵이 아닌 이전 (첫 번째) 비트 맵과 연결된 그래픽 핸들 (2 단계)을 계속 사용합니다.

    이전 (첫 번째) 비트 맵이 아닌 새로운 (두 번째) 비트 맵과 연결된 그래픽 핸들을 사용해야합니다.