I’m having an issue with DrawTextEx. When using Align = DT_RIGHT and font “Arial”, the text exceeds the rectangle.
This is the code I used to reproduce the issue:
procedure TForm2.FormShow(Sender: TObject);
var
LRect: TRect;
LString : string;
LMetaCanvas: TMetafileCanvas;
LAlign: integer;
LParams: TDrawTextParams;
begin
LMetaCanvas := TMetafileCanvas.Create(Image1.Picture.Metafile, 0);
LRect := Rect(10, 10, 200, 200);
LMetaCanvas.Brush.Color := clWhite;
LMetaCanvas.Brush.style := bsSolid;
LMetaCanvas.Rectangle(LRect.Left, LRect.Top, LRect.Right, LRect.Bottom);
LMetaCanvas.Font.Name := 'Arial';
LMetaCanvas.Font.Size := 10;
LMetaCanvas.Brush.Color := clBlack;
LMetaCanvas.Brush.Style := bsClear;
LString := '111111111111111112';
LParams.cbSize := SizeOf(LParams);
LParams.iTabLength := 0;
LParams.iLeftMargin := 0;
LParams.iRightMargin := 0;
LParams.uiLengthDrawn := Length(LString);
LAlign := DT_RIGHT or DT_NOPREFIX or DT_EDITCONTROL or DT_EXPANDTABS or DT_NOCLIP;
DrawTextEx(
LMetaCanvas.Handle,
PChar(LString),
Length(LString),
LRect,
LAlign,
@LParams);
LMetaCanvas.Free;
end;
Without DT_NOCLIP, the characters which are outside the rectangle aren’t even displayed.
I’m using Delphi 10.2 on Windows 10 Pro, but I’ve been facing this issue also on Delphi XE3 and Delphi 2007.
Edit: I tried to use DT_CALCRECT, but I’m not sure this is the correct way… This is the code I used:
LAlign := DT_RIGHT or DT_NOPREFIX or DT_EDITCONTROL or DT_EXPANDTABS or DT_NOCLIP or DT_CALCRECT;
DrawTextEx(
LMetaCanvas.Handle,
PChar(LString),
Length(LString),
LRect,
LAlign,
@LParams);
LAlign := DT_RIGHT or DT_NOPREFIX or DT_EDITCONTROL or DT_EXPANDTABS or DT_NOCLIP;
DrawTextEx(
LMetaCanvas.Handle,
PChar(LString),
Length(LString),
LRect,
LAlign,
@LParams);
LMetaCanvas.Free;
end;
After first call to DrawTextEx, LRect became (10, 10, 120, 26), which makes it smaller than how I configured it at the beginning (10, 10, 200, 200). The text is drawn aligned to the left (I guess that’s because LRect was changed in order to fit the text) and still, without DT_NOCLIP I can’t see the last numbers.
Edit: The project where this issue emerged requires a TMetaFileCanvas
(for other purposes) and uses DrawTextEx
to display amounts (which have to be aligned to the right), so unfortunately I can’t change canvas type, alignment or text. Using a different font like Arial Unicode MS (which doesn’t seem to have issues) would mean changing a huge amount of existing reports, so I’d rather avoid this solution..
As @SertacAkyuz suggested, adding a zero width space at the end of LString
solved the issue.
LString := LString + #$200B;