Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rorz/c279b0acb8659f52c04ae3f86e700571 to your computer and use it in GitHub Desktop.
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+
//
// 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