I wrote something similar, but in Pascal:Difference here is that it goes by width in pixels.
Code:
procedure WrapText(wtText: String); var LStart, LLength: Integer; begin //Only wrap if it is longer than the available width if(FTextWrap)and(FContent.Canvas.TextWidth(wtText)+XPos>W)then begin //Start at the beginning LStart:=1; //And continue until we are out of characters while LStart<Length(wtText) do begin //Length of remaining string (if LStart+LLength are bigger than the string //length, then it'll just go to the end of the string) LLength:=Length(wtText); //Reduce the length until it'll fit while(FContent.Canvas.TextWidth(Copy(wtText,LStart,LLength))+XPos>W) and(LLength>1)do dec(LLength); //Then print what we can PrintText(Copy(wtText,LStart,LLength)); //And move the starting position along inc(LStart,LLength); //If there are more characters left, then do a CR and LF if LStart<=Length(wtText) then begin //Move the Y pointer downwards inc(YPos,FContent.Canvas.TextHeight(wtText)+FLineSpace); //Reset X pointer XPos:=FLineSpace; end; end; //The string is only a single character, but still won't fit, so CR LF if Length(wtText)=1 then begin //Move the Y pointer downwards inc(YPos,FContent.Canvas.TextHeight(wtText)+FLineSpace); //Reset X pointer XPos:=FLineSpace; end; //The starting point is the last character, so print and move along if LStart=Length(wtText) then PrintText(Copy(wtText,LStart)); end else PrintText(wtText);//No text wrapping end;
Statistics: Posted by geraldholdsworth — Thu Apr 04, 2024 10:14 pm