Skip to content

Instantly share code, notes, and snippets.

@joethephish
Created November 22, 2018 13:17
Show Gist options
  • Save joethephish/7fe29f588a62b11cbd482e4849b121b1 to your computer and use it in GitHub Desktop.
Save joethephish/7fe29f588a62b11cbd482e4849b121b1 to your computer and use it in GitHub Desktop.
Example of centre alignment using SLayout
public class ExampleTextView {
public bool alignCentre;
// ... various fields, grab the SLayout as "layout" ...
// populate this list
List<SLayout> _wordLayouts;
// Lays out the words and returns the size used.
public Vector2 LayoutWords() {
float maxLineWidth = 0;
float fitWidth = layout.width;
float maxWordsWidthPerLine = fitWidth - padding.horizontal;
while(currentWordIdx < _wordLayouts.Count) {
int numWordsOnLine = 0;
// Calculate width of this line for alignment reasons
float lineWidth = 0.0f;
for(int lineWordIdx = currentWordIdx; lineWidth < maxWordsWidthPerLine && lineWordIdx < _wordLayouts.Count; lineWordIdx++) {
float lineWordWidth = _wordLayouts[lineWordIdx].width;
float lineWidthAfterNewWord = lineWidth + lineWordWidth;
if( lineWordIdx > currentWordIdx ) lineWidthAfterNewWord += spaceWidth;
// Does this word fit on the line?
if (lineWidthAfterNewWord < maxWordsWidthPerLine) {
lineWidth = lineWidthAfterNewWord;
numWordsOnLine++;
}
// Force the first word in if it's long, even if it doesn't fit
else if (numWordsOnLine == 0) {
numWordsOnLine++;
break;
}
// Run out of space
else {
break;
}
}
if( lineWidth > maxLineWidth )
maxLineWidth = lineWidth;
float indentDueToAlign = alignCentre ? 0.5f * (fitWidth - lineWidth) : padding.left;
float currX = indentDueToAlign;
for(int i=0; i<numWordsOnLine; i++) {
var wordLayout = _wordLayouts[currentWordIdx + i];
float wordWidth = wordLayout.width;
wordLayout.position = new Vector2(currX, currY);
currX += spaceWidth + wordWidth;
}
// Next line
currY += lineHeight;
currentWordIdx += numWordsOnLine;
}
if( maxLineWidth > fitWidth ) maxLineWidth = fitWidth;
return new Vector2(maxLineWidth + padding.horizontal, currY + padding.bottom);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment