Forked from aral/NSView+ChangeAnchorPointWithoutMakingTheLayerJump.swift
Last active
June 17, 2018 00:51
-
-
Save rorz/c279b0acb8659f52c04ae3f86e700571 to your computer and use it in GitHub Desktop.
A replacement for the anchorPoint property that doesn’t make the layer jump. Swift 4+
This file contains 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 | |
// | |
// New: Converted to Swift 4+ | |
func setAnchorPoint (anchorPoint:CGPoint) | |
{ | |
if let layer = self.layer | |
{ | |
var newPoint = CGPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y) | |
var oldPoint = CGPoint(x: self.bounds.size.width * layer.anchorPoint.x, y: self.bounds.size.height * layer.anchorPoint.y) | |
newPoint = newPoint.applying(layer.affineTransform()) | |
oldPoint = oldPoint.applying(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