Skip to content

Instantly share code, notes, and snippets.

@jordandobson
Last active July 7, 2017 21:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordandobson/7df22e6667ac6e25b6de075c0626a9c5 to your computer and use it in GitHub Desktop.
Save jordandobson/7df22e6667ac6e25b6de075c0626a9c5 to your computer and use it in GitHub Desktop.
Get Bounding Layer for Rotated Layer
getBoundingLayerForRotatedLayer = (layer) ->
tr = "topRight"; bl = "bottomLeft"; tl = "topLeft"; br = "bottomRight";
center = x: layer.midX, y: layer.midY
size = w: layer.width, h: layer.height
rotation = layer.rotation
corners =
"#{tr}": x: (size.w/2), y: (size.h/2)
"#{bl}": x: -(size.w/2), y: -(size.h/2)
getRotatedPoint = (p) ->
return {
x: center.x + (p.x * Math.cos rotation) - (p.y * Math.sin rotation)
y: center.y + (p.x * Math.sin rotation) - (p.y * Math.cos rotation)
}
calculateFrameFromOppositePoints = (op) ->
cornerPoints = "#{tl}": null, "#{bl}": null, "#{tr}": null, "#{br}": null
# Update with opposite points
cornerPoints[label] = point for label, point of op
# Fill in Missing Points
for label, point of cornerPoints when not point?
cornerPoints[label] =
x: cornerPoints[(if label is tl then bl else tr)].x
y: cornerPoints[(if label is br then bl else tr)].y
# Return Frame calculated from all points
return {
x: cornerPoints[tl].x,
y: cornerPoints[tl].y,
width: cornerPoints[tr].x - cornerPoints[tl].x,
height: cornerPoints[bl].y - cornerPoints[tl].y
}
# Get Rotated Point for Two corners
corners[corner] = getRotatedPoint point for corner, point of corners
# Return layer with frame applied
return new Layer parent: layer.parent, visible: false, frame: calculateFrameFromOppositePoints corners
@jordandobson
Copy link
Author

jordandobson commented Jul 7, 2017

Give it a rotated layer and get a layer back that is a bounding Box for the original layer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment