Home > Enterprise >  Custom Measure String in C# without Graphics.MeasureString
Custom Measure String in C# without Graphics.MeasureString

Time:04-07

I am trying to create an Image with a Caption/Text on it for Youtube-Thumbnails.

Following Rules are defined:

  • The Text is the Title of the Video and always changes from Thumbnail to Thumbnail.
  • The Porgram uses a pre-defined Text-Width which must not be touched by the Text on the Image.
  • The Text should be as close to the pre-defined with as possible.

So my thoughts were that I would use Graphics.MeasureString to be able to track the Width of the String on the Image and increase the Font-Size and repeat this until the pre-defined Width is closely reached but not touched.

But I have tested it with MeasureString and found out that it isn't that accurate. And also found confirmation here: enter image description here

But the exact String width is 1742 instead of the width of my Image 1920 which should be more or less the same at this moment.

So, why is the Text nearly as wide as the Image but doesn't have the same width?

CodePudding user response:

highestWidth = redPixelMatrix.Keys.Count; This will just count the number of columns containing red pixels, excluding any spaces in the text. You presumably want the minimum and maximum indices.

I.e.

var minX = int.MaxValue;
var maxX = int.MinValue;
// Loops over rows & columns
    // Check if pixel is red
        if(i > maxX) maxX = i;
        if(i <  minX) minX = i;

If you only want the text width and not the bounds you can just do maxX - minX.

  • Related