標籤:
源:Delphi中建立指定大小字型和讀取該字型點陣資訊的函數
Delphi中建立指定大小字型和讀取該字型點陣資訊的函數
Thermometer Email: [email protected]
由於要控制硬體,需要把向量的漢字轉化為點陣資訊寫入eprom或在液晶屏上顯示,因此用Delphi寫了如下的函數,可以把指定的一個漢字(兩個字元)轉化為點陣資訊儲存到檔案,每個點對應一個二進位位,有文字資訊該位為1,否則為0。
目前該函數可以產生指定大小的漢字並可讀取點陣字模資訊儲存到檔案。
如ConvertToMatrix(Pchar(‘北‘),6,18,‘Font.dat‘)將產生12*18點陣檔案Font.dat,其中儲存漢字‘北’的字模資訊。檔案格式是從上到下,先行後列,如,第一行儲存為00 00,第二行是90 00 (均是16進位,餘下個行類推)
//轉化一個漢字為點陣資訊。參數Text為一個漢字,ChrWidth是字元寬,漢字是兩個字元大小,所以如果要產生寬是12的漢字則ChrWidth為6,ChrWidth目前最多是8,因為大多數的硬體使用的點陣資訊是16以下ChrHeight是漢字的高,SaveFileName是儲存該漢字點陣資訊的檔案名稱。function ConvertToMatrix(Text:PChar; ChrWidth,ChrHeight:Byte; SaveFileName:Pchar):Bool;type PBITMAPINFO=^TBitmapInfo;var TempBmp:TBitmap; lpvSBits,lpvDBits:Pchar; dOffset,sOffset:integer; DC:HDC; TheFont: HFont; BMIInfo:PBITMAPINFO; DS: TDIBSection; BMIbuf:array[0..2047]of byte; i,j:integer;//迴圈控制 wData:WORD;//儲存字型每行的點陣資訊,最多16位,不足16位忽略多餘的高位 MemoryStream:TMemoryStream;begin //大於一個字退出 if Length(Text)>2 then begin ShowMessage(‘請轉化一個漢字!‘); Result:=False; Exit; end; //參數合理否 if (ChrWidth=0) or (ChrHeight=0) or (SaveFileName = ‘‘) then begin ShowMessage(‘參數錯誤!‘); Result:=False; Exit; end; //建立流 MemoryStream:=TMemoryStream.Create; //建立臨時檔案 TempBmp:=TBitmap.Create; //設定為256色 TempBmp.PixelFormat:= pf8bit; //設定圖寬度 TempBmp.Width:=ChrWidth * Length(Text); //設定圖高度 TempBmp.Height:= ChrHeight; //得到BMP檔案HDC DC:=TempBmp.Canvas.Handle; //建立邏輯字型 TheFont := CreateFont(ChrHeight,ChrWidth, 0, 0, 400, 0, 0, 0, GB2312_CHARSET, Out_Default_Precis, Clip_Default_Precis, Default_Quality, Default_Pitch OR FF_SCRIPT, ‘script‘); //指定字型給DC SelectObject(DC,TheFont); //寫入指定字串 TextOut(DC,0,0,Pchar(Text),Length(Text)); //釋放邏輯字型 DeleteObject(TheFont); //取得Bmp資訊到lpvSBits BMIInfo:=PBITMAPINFO(@BMIbuf); //分配記憶體 lpvSBits:=AllocMem(TempBmp.Width*TempBmp.Height); lpvDBits:=AllocMem(TempBmp.Width*TempBmp.Height); //建立程式螢幕相容的DC DC := CreateCompatibleDC(0); //返回指定的BMP資訊到DS中儲存 GetObject(TempBmp.Handle, SizeOf(DS), @DS); //讀取頭資訊 BMIInfo.bmiHeader:=ds.dsBmih; //讀入DIB GetDIBits(DC, TempBmp.Handle, 0, ds.dsBmih.biHeight,lpvSBits, BMIInfo^ , DIB_RGB_COLORS); //倒置映像 for i:=0 to TempBmp.Height-1 do begin sOffset:=i*TempBmp.Width; dOffset:=(TempBmp.Height-i-1)*TempBmp.Width; CopyMemory(lpvDBits+dOffset,lpvSBits+sOffset,TempBmp.Width); end; //儲存檔案 for i:=0 to TempBmp.Height-1 do begin wData:=0; for j:=0 to TempBmp.Width-1 do begin //ShowMessage(inttostr(ord((lpvDBits+i*TempBmp.Width+j)^))); if ord((lpvDBits+i*TempBmp.Width+j)^)=0 then begin wData:=(wData shl 1)OR 1; end else begin wData:=(wData shl 1)OR 0; end; end; MemoryStream.Write(wData,SizeOf(wData)); end; MemoryStream.SaveToFile(SaveFileName); MemoryStream.Free;//TempBmp.SaveToFile(‘temp.bmp‘)可刪除,存‘temp.bmp‘檔案的目的只是為對比察看 TempBmp.SaveToFile(‘temp.bmp‘); TempBmp.Free; FreeMem(lpvSBits); FreeMem(lpvDBits); result:=True;end;
附:本文全部為原創內容,如果您使用中對程式做了改動請發給作者一分[email protected];引用時請註明原創作者是Thermometer並寫清楚原創者的eMail,謝謝。
Delphi中建立指定大小字型和讀取該字型點陣資訊的函數(轉)