Last active
August 29, 2015 14:17
-
-
Save acwright/b1523f804b9bd8922fbb to your computer and use it in GitHub Desktop.
Center view with aspect ratio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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