Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Created February 20, 2018 00:10
Show Gist options
  • Save steveruizok/5751a18717c68709aee34e17e0161fc9 to your computer and use it in GitHub Desktop.
Save steveruizok/5751a18717c68709aee34e17e0161fc9 to your computer and use it in GitHub Desktop.
# Set a layer's contraints to its parent
# @example Utils.constrain(layer, {left: true, top: true, asepectRatio: true})
Utils.constrain = (layer, opts...) ->
if not layer.parent? then throw 'Utils.constrain requires a layer with a parent.'
options =
left: false,
top: false,
right: false,
bottom: false,
height: false
width: false
aspectRatio: false
for opt in opts
options[opt] = true
values =
left: if options.left then layer.x else null
height: layer.height
centerAnchorX: layer.midX / layer.parent?.width
width: layer.width
right: if options.right then layer.parent?.width - layer.maxX else null
top: if options.top then layer.y else null
centerAnchorY: layer.midY / layer.parent?.height
bottom: if options.bottom then layer.parent?.height - layer.maxY else null
widthFactor: null
heightFactor: null
aspectRatioLocked: options.aspectRatio
unless options.top and options.bottom
if options.height
values.heightFactor = layer.height / layer.parent?.height
unless options.left and options.right
if options.width
values.widthFactor = layer.width / layer.parent?.width
layer.constraintValues = values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment