This project has moved. For the latest updates, please go here.

Drawing text

Dec 20, 2013 at 11:54 AM
Hi,

I'm trying to draw text onto a transparent image and then crop the image to the text's bounding box. I have the following code (please see below) but (a) I'm specifying the image size which I'd like to avoid as I wont know the text size in advance and (b) I'm not cropping the image although the area I'm interested in is represented by the (bounding) box. Any help would be greatly appreciated.
Using image As New MagickImage(System.Drawing.Color.Transparent, 500, 150)
   image.Format = MagickFormat.Png
   Dim font As New DrawableFont("Arial")
   Dim pointSize As New DrawablePointSize(50)
   Dim fillColor As New DrawableFillColor(System.Drawing.Color.Black)
   Dim strokeColor As New DrawableStrokeColor(System.Drawing.Color.Red)
   Dim strokeWidth As New DrawableStrokeWidth(1)
   Dim strokeAntialias As New DrawableStrokeAntialias(True)
   Dim textAntialias As New DrawableTextAntialias(True)
   Dim text As New DrawableText(10, 100, "Hello World")
   Dim params() As ImageMagick.Drawable = {font, pointSize, strokeColor, fillColor, strokeWidth, strokeAntialias, textAntialias, text}
   image.Draw(params)
   Dim box As ImageMagick.MagickGeometry = image.BoundingBox
   image.Write("helloworld.png")
End Using
Thanks
Coordinator
Dec 20, 2013 at 12:45 PM
You can determine the size of your text with the FontTypeMetrics method. But you should also consider using Pango (http://www.imagemagick.org/Usage/text/#pango_markup), this can make it easier for you.
Dec 20, 2013 at 6:44 PM
Hi,

Thanks. Using the FontTypeMetric I can create an image in proportion to the text I need to draw. I'm still not sure how to crop the image correctly though. If I don't crop my image and just write it to file as outlined in my original post then the image is ok but will have a larger border then I need around it. If I call the Trim method immediately before the Write method then things appear ok but if I open the file in an image editor (e.g. GIMP) the font appears offset from the transparent background (i.e. it's only partially visible). I'm not sure if its the same thing but in the docs there's talk of using "+repage" immediately after "-crop". How do you do the same thing using Magick.NET?

Thanks
Coordinator
Dec 20, 2013 at 7:17 PM
You can reset the page (repage) like this:
image.Page = new MagickGeometry(0, 0);