UPDATED: Fixed Image Size, Thanks to Christof Wollenhaupt
More than once I've seen people asking to create images containing some text. The sample below is really very simple.
- Creates a font
- Measures the space that the text will need
- Creates an image with the needed size
- Draws the string
- Saves to disk
IMPORTANT
Requires VFP9 and GdiPlusX to run.
Please make sure that you have the latest version, because this sample may be using some functions that were added or fixed recently.
http://www.codeplex.com/VFPX/Wiki/View.aspx?title=GDIPlusX&referringTitle=Home
DO LOCFILE
("System.prg")
WITH _SCREEN.System.Drawing
LOCAL lcText
lcText = "GdiPlusX is Cool !!!"
* Create a Font
LOCAL loFont as xfcFont
loFont = _screen.system.Drawing.Font.New("Verdana", 32, .FontStyle.BoldItalic)
LOCAL loTmpBmp as xfcBitmap
loTmpBmp = .Bitmap.New(1,1)
* Retrieve the graphics object.
LOCAL loTmpGfx AS xfcGraphics
loTmpGfx = .Graphics.FromImage(loTmpBmp)
* Measure the String
* Get the size required for our text
LOCAL loSize as xfcSize
loSize = loTmpGfx.MeasureString(lcText, loFont)
LOCAL loNewBmp as xfcBitmap
loNewBmp = .Bitmap.New(loSize.Ceiling)
LOCAL loNewGfx as xfcGraphics
loNewGfx = .Graphics.FromImage(loNewBmp)
* Clear the background to Yellow
loNewGfx.Clear(.Color.Yellow)
* Create a solid brush
LOCAL loBrush as xfcSolidBrush
loBrush = .SolidBrush.New(.Color.FromRGB(255,0,0)) && Red
* Create an StringFormat object in order to draw the sting centered in the image
LOCAL loStringFmt as xfcStringFormat
loStringFmt = .StringFormat.New()
loStringFmt.Alignment = .StringAlignment.Center
* Create a Rectangle with the measures of the Bitmap
LOCAL loRect as xfcRectangleF
loRect = loNewBmp.GetBounds()
* Draw the String
loNewGfx.DrawString(lcText, loFont, loBrush, loRect, loStringFmt)
* Finally save the image
loNewBmp.Save("c:\MyText.Png", .Imaging.ImageFormat.Png)
* Show the image
RUN /N Explorer.exe c:\Mytext.Png
ENDWITH