Created
May 5, 2018 18:27
-
-
Save marcosgriselli/ec284ae72c4f0162048eee6a8434d36d to your computer and use it in GitHub Desktop.
Morph a view to another view's via transforms or frame
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
// | |
// Morphable.swift | |
// Morphable | |
// | |
// Created by marcosgriselli on 05/05/2018. | |
// Copyright (c) 2018 marcosgriselli. All rights reserved. | |
// | |
import UIKit | |
public extension UIView { | |
func transformTo(_ view: UIView, scale: CGFloat = 1) { | |
guard let convertedFrame = superview?.convert(view.frame, from: view.superview) else { | |
fatalError("Your views are not correctly added to the hirearchy") | |
} | |
transform = transformRect(from: frame, to: rect * scale) | |
} | |
func morphRectTo(_ view: UIView, scale: CGFloat = 1) { | |
guard let convertedFrame = superview?.convert(view.frame, from: view.superview) else { | |
fatalError("Your views are not correctly added to the hirearchy") | |
} | |
alpha = view.alpha | |
layer.cornerRadius = view.layer.cornerRadius * scale | |
frame = convertedFrame * scale | |
} | |
private func transformRect(from source: CGRect, to destination: CGRect) -> CGAffineTransform { | |
return CGAffineTransform.identity | |
.translatedBy(x: destination.midX - source.midX, | |
y: destination.midY - source.midY) | |
.scaledBy(x: destination.width / source.width, | |
y: destination.height / source.height) | |
} | |
} | |
fileprivate extension CGRect { | |
static func *(lhs: CGRect, rhs: CGFloat) -> CGRect { | |
let scaledWidth = lhs.width * rhs | |
let scaledHeight = lhs.height * rhs | |
let x = lhs.origin.x + (lhs.width - scaledWidth) / 2 | |
let y = lhs.origin.y + (lhs.height - scaledHeight) / 2 | |
return CGRect(x: x, y: y, width: scaledWidth, height: scaledHeight) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment