Recent

Author Topic: Add CocoaWidgetSet.GetTextExtentPointF  (Read 1933 times)

Alextp

  • Hero Member
  • *****
  • Posts: 1552
    • UVviewsoft
Add CocoaWidgetSet.GetTextExtentPointF
« on: November 11, 2021, 11:40:20 am »
I need the Cocoa method to get _floating number_ width of a given string, ie Double value. I suggest to add to Cocoa. I tried this code, and my demo crashes (I cannot debug it yet, problem with fpcupdeluxe on macOS)

Pls correct my code and add it to Laz.

1) cocoawinapi.inc

Code: Pascal  [Select][+][-]
  1. function TCocoaWidgetSet.GetTextExtentPointF(DC: HDC; Str: PChar; Count: Integer; out AWidth, AHeight: Double): Boolean;
  2. var
  3.   ctx : TCocoaContext;
  4. begin
  5.   {$IFDEF VerboseWinAPI}
  6.     DebugLn('[TCocoaWidgetSet.GetTextExtentPointF] DC: %x Str: %s Count: %d', [DC, Str, Count]);
  7.   {$ENDIF}
  8.   ctx:=CheckDC(DC);
  9.   Result:=Assigned(ctx);
  10.   if not Assigned(ctx) then Exit(False);
  11.   Result := ctx.GetTextExtentPointF(Str, Count, AWidth, AHeight);
  12.   {$IFDEF VerboseWinAPI}
  13.     DebugLn('[TCocoaWidgetSet.GetTextExtentPointF] Size: %d,%d', [Size.cx, Size.cy]);
  14.   {$ENDIF}
  15. end;  

2) cocoagdiobjects.pas

Copy-paste from GetTextExtentPoint!

Code: Pascal  [Select][+][-]
  1. function TCocoaContext.GetTextExtentPointF(AStr: PChar; ACount: Integer; out AWidth, AHeight: Double): Boolean;
  2. var
  3.   s : NSString;
  4.   M : NSMutableAttributedString;
  5.   r : NSRect;
  6. begin
  7.   AWidth := 0;
  8.   AHeight := 0;
  9.   {FText.SetText(AStr, ACount);
  10.   Size := FText.GetSize;
  11.   Result := True;}
  12.   S := NSString( CFStringCreateWithBytesNoCopy(nil, AStr, ACount, kCFStringEncodingUTF8,
  13.     false,
  14.     kCFAllocatorNull));
  15.   Result := Assigned(S);
  16.   if not Result then Exit;
  17.  
  18.   M := NSMutableAttributedString.alloc.initWithString(S);
  19.   Result := Assigned(M);
  20.   if Result then
  21.   begin
  22.     FText.SetFontToStr(M);
  23.     r := M.boundingRectWithSize_options(NSMakeSize(MaxInt, MaxInt), 0);
  24.  
  25.     AWidth := r.size.width;
  26.     AHeight := r.Size.height;
  27.     M.release;
  28.   end;
  29.   CFRelease(S);
  30. end;
  31.  

3) demo to test it. Zip.

Alextp

  • Hero Member
  • *****
  • Posts: 1552
    • UVviewsoft
Re: Add CocoaWidgetSet.GetTextExtentPointF
« Reply #1 on: November 14, 2021, 07:50:35 pm »
I fixed the demo by myself. Now I see that char-width of '0' and all other ASCII chars is 7.801 pixels on macOS 10.8.
For several fonts: Courier, Monaco, Liberation Mono.
The same for all ASCII!

 

TinyPortal © 2005-2018