skip to Main Content

Is it possible to know text dimensions in Matlab?

For example, is it possible to know the following measures

enter image description here

UPDATE

I need no image processing. I know I can deduce the location of baseline of “g” letter with simple commonly used artificial intelligence 🙂 This is not what I want. I want Matlab give me what it has, namely, the font metrics. If it can’t then the answer is “Matlab can’t”.

UPDATE 2

Currently I am trying to do via Java interface like this

figure_h=figure;
axes_h = axes('Position', [0, 0, 1, 1], 'Units', 'pixels');

s='g';
x=200;
y=200;

fontName = 'Times New Roman';
fontSize = 48; % will be in points

text('String', s, 'Units', 'pixels', 'Position', [x y], 'FontName', fontName, 'FontUnits', 'points', 'FontSize', fontSize);

% make equivalent Java font
jFont=java.awt.Font(fontName,java.awt.Font.PLAIN,fontSize);

% accessing metrics object
jFrame = get(figure_h,'JavaFrame');
jCanvas = jFrame.getAxisComponent;
jGraphics=jCanvas.getGraphics;
jMetrics=jGraphics.getFontMetrics;

%rectangle('Position', [x, y, jMetrics.charWidth(s), jMetrics.getDescent]);

but getting null pointer exception at getFontMetrics.

2

Answers


  1. You can get an image of the font using

    fh = figure;
    text( 0, 0, 'frog', 'FontName', 'tahoma', 'FontSize', 30 );
    axis off;
    f = getframe( fh );
    bw = rgb2gray(f.cdata)==0;
    

    Now you have bw as a binary image of the fonts (in this example tahoma size 30). You may proceed using regionprops (especially 'BoundingBox' property) to compute the desired measures (in pixels).

    Login or Signup to reply.
  2. If the intention is to get the font metrics, you need to create a dummy Graphics object like a TextField, something like this

    fontName = 'Times New Roman';
    fontSize = 48; % will be in points
    
    jText = java.awt.TextField('');
    jFont = java.awt.Font(fontName, java.awt.Font.PLAIN, fontSize);
    jMetrics = jText.getFontMetrics(jFont);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search