Skip to content

Instantly share code, notes, and snippets.

@chrisladd
Created February 9, 2016 19:56
Show Gist options
  • Save chrisladd/70f73c11d9b08672552f to your computer and use it in GitHub Desktop.
Save chrisladd/70f73c11d9b08672552f to your computer and use it in GitHub Desktop.
Text Rendering for Sketch
// text.js
function replaceSubstring(inSource, inToReplace, inReplaceWith) {
var outString = inSource;
while (true) {
var idx = outString.indexOf(inToReplace);
if (idx == -1) {
break;
}
outString = outString.substring(0, idx) + inReplaceWith +
outString.substring(idx + inToReplace.length);
}
return outString;
}
function lightDecodeText(text) {
text = replaceSubstring(text, ''', '’');
return text;
}
function configureLayerForStyle(textLayer, style) {
var config = configForTextStyleWithName(style);
if (config.font) {
textLayer.setFontPostscriptName(config.font);
};
if (config.fontSize) {
textLayer.setFontSize(config.fontSize);
};
if (config.lineSpacing) {
textLayer.setLineSpacing(config.lineSpacing);
};
if (config.alignment) {
textLayer.setTextAlignment(config.alignment);
};
if (config.color) {
textLayer.setTextColor(MSColor.colorWithSVGString(config.color));
};
}
function textLayerWithText(text, style, x, y, width) {
// https://github.com/sketchplugins/plugin-requests/blob/master/Toggle%20Text%20Width.sketchplugin
text = lightDecodeText(text);
var initialRect = NSMakeRect(x, y, width, 2000);
var textLayer = [[MSTextLayer alloc] initWithFrame:initialRect];
[textLayer setTextBehaviour:1];
textLayer.name = text;
textLayer.setStringValue(text);
configureLayerForStyle(textLayer, style);
var doc = _context.document;
doc.currentPage().addLayers([textLayer]);
var frame = textLayer.frame();
frame.setWidth(width);
var layoutManager = textLayer.layoutManager();
var textContainer = textLayer.textContainer();
[layoutManager ensureLayoutForTextContainer:textContainer];
var usedRect = [layoutManager usedRectForTextContainer:textContainer];
frame.setSize(usedRect.size);
frame.setWidth(width);
return textLayer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment