I want to rotate a image in this code would be pic1. I placed a image below of what I am exactly looking for. I don't want to rotate the entire image I want to rotate from the bottom left corner of the rectangle 90 degrees. You can see specifically what I am talking about in the green circle. The rotation should take place in the button function.
import UIKit
class ViewController: UIViewController {
var pic1 = UIImageView()
var rot = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
pic1.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pic1)
rot.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(rot)
rot.backgroundColor = .blue
pic1.image = UIImage(named: "badMan.png")
NSLayoutConstraint.activate(
[
pic1.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.50),
pic1.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1),
pic1.topAnchor.constraint(equalTo: view.topAnchor),
pic1.leadingAnchor.constraint(equalTo: view.leadingAnchor),
rot.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.50),
rot.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1),
rot.topAnchor.constraint(equalTo: pic1.bottomAnchor),
rot.leadingAnchor.constraint(equalTo: view.leadingAnchor),
])
self.view.addSubview(pic2)
rot.addTarget(self, action: #selector(roate), for: .touchDown)
}
@objc func roate(){
}
}
You Can make a extension of uiview to set anchor point :
extension UIView{
func setAnchorPoint(anchorPoint: CGPoint) {
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 * self.layer.anchorPoint.x, y: self.bounds.size.height * self.layer.anchorPoint.y)
newPoint = newPoint.applying(self.transform)
oldPoint = oldPoint.applying(self.transform)
var position : CGPoint = self.layer.position
position.x -= oldPoint.x
position.x += newPoint.x;
position.y -= oldPoint.y;
position.y += newPoint.y;
self.layer.position = position;
self.layer.anchorPoint = anchorPoint;
}
}
Then set anchor point in viewDidLoad:
// set anchor point, below code will set anchor point in the bottom(y) middle (x) of myView
self.myView.setAnchorPoint(anchorPoint: CGPoint(x: 0.5, y: 1))
call rotate now
func Rotate(){
let rotation = UIViewPropertyAnimator(duration: 1, curve: .linear, animations: {
self.myView.transform = self.myView.transform.rotated(by: CGFloat.pi/2)
})
rotation.startAnimation()
}