Skip to content

Instantly share code, notes, and snippets.

@acwright
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save acwright/b1523f804b9bd8922fbb to your computer and use it in GitHub Desktop.

Select an option

Save acwright/b1523f804b9bd8922fbb to your computer and use it in GitHub Desktop.
Center view with aspect ratio
func centerViewOn(point: CGPoint) {
if let layer = self.layers.first?.layer {
let viewSize = self.view!.bounds.size
let ratioWidth = self.size.height / viewSize.height
let newWidth = viewSize.width * ratioWidth
let ratioHeight = self.size.width / viewSize.width
let newHeight = viewSize.height * ratioHeight
var offsetX = (self.size.width - newWidth) / 2
var offsetY = (self.size.height - newHeight) / 2
if offsetX < 0 {
offsetX = 0
}
if offsetY < 0 {
offsetY = 0
}
let x = point.x.clamped((self.size.width / 2) - offsetX, (layer.layerSize().width - self.size.width / 2) + offsetX)
let y = point.y.clamped((self.size.height / 2) - offsetY, (layer.layerSize().height - self.size.height / 2) + offsetY)
self.world.position = CGPointMake(-x, -y)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment