Skip to content

Instantly share code, notes, and snippets.

@LukeFinch
Created July 2, 2020 13:17
Show Gist options
  • Save LukeFinch/cdf52a45270e31d1de618348b80db949 to your computer and use it in GitHub Desktop.
Save LukeFinch/cdf52a45270e31d1de618348b80db949 to your computer and use it in GitHub Desktop.
Sketch Script to crop text to remove whitespace on the line.
var doc = context.document
var Text = require('sketch/dom').Text
var page = MSDocument.currentDocument().currentPage();
var fontFamilies = ['Monaco','Helvetica-Black']
fontFamilies.forEach(fam => {console.log(getCropsForFontFamily(fam))})
function getCropsForFontFamily(fontFamily){
let family = fontFamily
let size = 16
var text = new Text({
text: "T",
parent: page
})
var predicate = NSPredicate.predicateWithFormat("objectID == %@", text.id)
var result = page.children().filteredArrayUsingPredicate(predicate);
let textLayer = result[0]
textLayer.fontPostscriptName = family
textLayer.fontSize = size
let defaultLineHeight = getDefaultLineHeightForFont(textLayer.fontPostscriptName(),textLayer.fontSize())
let defaultLineHeightEm = defaultLineHeight/size
let bounds = textLayer.pathInFrame().bounds()
let t = -bounds.origin.y/size
let b = -((defaultLineHeight-bounds.size.height)-bounds.origin.y)/size
text.remove()
return {'family':fontFamily,'top':t,'bottom':b,'defaultLineHeight':defaultLineHeightEm}
}
function getDefaultLineHeightForFont(fontFamily, size) {
let font = NSFont.fontWithName_size(fontFamily, size);
let lm = NSLayoutManager.alloc().init();
return lm.defaultLineHeightForFont(font);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment