Created
February 9, 2016 19:56
-
-
Save chrisladd/70f73c11d9b08672552f to your computer and use it in GitHub Desktop.
Text Rendering for Sketch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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