Created
July 18, 2015 21:01
-
-
Save aral/a6f1de2bc48bc0602c9c to your computer and use it in GitHub Desktop.
A replacement for the anchorPoint property that doesn’t make the layer jump
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
// | |
// NSView+ChangeAnchorPointWithoutMakingTheLayerJump.swift | |
// | |
// Setting .anchorPoint on a layer makes the layer jump which is most | |
// likely not what you want. This extension fixes that. Useful for Core Animation. | |
// | |
// Usage: (e.g., to set the anchor point to the centre) | |
// | |
// myView.setAnchorPoint(CGPointMake(0.5, 0.5)) | |
// | |
// Created by Aral Balkan on 18/07/2015. | |
// Copyright (c) 2015 Ind.ie. Released under the MIT License. | |
// | |
import Cocoa | |
extension NSView | |
{ | |
// | |
// Converted to Swift + NSView from: | |
// http://stackoverflow.com/a/10700737 | |
// | |
func setAnchorPoint (anchorPoint:CGPoint) | |
{ | |
if let layer = self.layer | |
{ | |
var newPoint = CGPointMake(self.bounds.size.width * anchorPoint.x, self.bounds.size.height * anchorPoint.y) | |
var oldPoint = CGPointMake(self.bounds.size.width * layer.anchorPoint.x, self.bounds.size.height * layer.anchorPoint.y) | |
newPoint = CGPointApplyAffineTransform(newPoint, layer.affineTransform()) | |
oldPoint = CGPointApplyAffineTransform(oldPoint, layer.affineTransform()) | |
var position = layer.position | |
position.x -= oldPoint.x | |
position.x += newPoint.x | |
position.y -= oldPoint.y | |
position.y += newPoint.y | |
layer.position = position | |
layer.anchorPoint = anchorPoint | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment