function t=ntext4(x,y,txt,NVargs) arguments x (1,1) double y (1,1) double txt string = "" end arguments NVargs.?matlab.graphics.primitive.Text end varargin = namedargs2cell(NVargs); t=text(x,y,txt,varargin{:}); % A variable to distinguish if the User changed the font size or these % functions. addprop(t,"ResizingText_changingFontSize"); %The original sizes needed for the calculation addprop(t,"ResizingText_rFontSize"); addprop(t,"ResizingText_rFontUnits"); addprop(t,"ResizingText_origAxisSize"); % A listener to listen for changes in the axes size addprop(t,"ResizingText_axisL"); t.ResizingText_changingFontSize = false; % Since we are building it we % aren't yet changing the size t.CreateFcn = @(S,~) initializeListeners(S); initializeListeners(t) end function initializeListeners(t) fontSizeListenerCB(t); % Stores values since we aren't change size. a = t.Parent; axisL = listener(a,"SizeChanged", @(~,~) axesListenerCB(t)); t.ResizingText_axisL=axisL; addlistener(t,"FontSize","PostSet", @(~,~) fontSizeListenerCB(t)); addlistener(t,"Parent","PostSet", @(~,~) parentListenerCB(t)); end function axesListenerCB(t) a = t.Parent; axesUnits = a.Units; fontUnits = t.FontUnits; a.Units = "pixels"; t.FontUnits = t.ResizingText_rFontUnits; rFontSize = t.ResizingText_rFontSize; axSize = t.ResizingText_origAxisSize; curhsize = axSize(3); curvsize = axSize(4); t.ResizingText_changingFontSize=true; t.FontSize = min(rFontSize*a.Position(3)/curhsize,rFontSize*a.Position(4)/curvsize); t.ResizingText_changingFontSize=false; t.FontUnits = fontUnits; a.Units = axesUnits; end function fontSizeListenerCB(t) if ~t.ResizingText_changingFontSize t.ResizingText_rFontSize = t.FontSize; t.ResizingText_rFontUnits = t.FontUnits; if ~isempty(t.Parent) a = t.Parent; aUnits = a.Units; a.Units = "pixels"; t.ResizingText_origAxisSize = t.Parent.Position; a.Units = aUnits; end end end function parentListenerCB(t) a = t.Parent; aUnits = a.Units; a.Units = "pixels"; t.ResizingText_origAxisSize = t.Parent.Position; a.Units = aUnits; end