Skip to content

Instantly share code, notes, and snippets.

@KevinGutowski
Last active June 13, 2020 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KevinGutowski/36c36decdfc82e172e41d285745accf8 to your computer and use it in GitHub Desktop.
Save KevinGutowski/36c36decdfc82e172e41d285745accf8 to your computer and use it in GitHub Desktop.
Attempting to Highlight First Letter
// Create a text layer within an artboard and select the layer to run properly
let Sketch = require('sketch')
let ShapePath = Sketch.ShapePath
let Rectangle = Sketch.Rectangle
// Removes old highlight layer so you can repeatedly run this code
let doc = Sketch.getSelectedDocument()
let oldHighlight = doc.pages[0].layers[0].layers.find(layer => layer.name=="highlight")
if (oldHighlight) { oldHighlight.remove() }
let selection = context.selection[0]
let jsSelect = Sketch.fromNative(selection)
let textLayerSize = selection.frame().size()
let attrString = selection.attributedStringValue()
let stringValue = selection.stringValue()
let textContainer = NSTextContainer.alloc().init()
textContainer.size = CGSizeMake(
textLayerSize.width,
Number.MAX_VALUE
);
let layoutManager = NSLayoutManager.alloc().init()
let textStorage = NSTextStorage.alloc().init()
textStorage.setAttributedString(attrString)
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
// Get frame of first letter
let frame = [layoutManager boundingRectForGlyphRange:NSMakeRange(0,1) inTextContainer:textContainer]
let rect = new Rectangle(frame)
// Reposition rect to origin of selection
rect.offset(selection.frame().x(),selection.frame().y())
let highlight = new ShapePath({
name: 'highlight',
frame: rect,
style: { fills: ["#FF0000"]},
parent: jsSelect.parent,
})
highlight.moveToBack()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment