Reputation: 1351
I'm trying to rotate an ImageView I have using CGAffineTransform
. Basically, what I want to happen is that every time the x-coordinate increases, I want the ImageView to rotate a little more.
I did the math and I want the ImageView to rotate 1.6º
every 1 x-coordinate
. This is what I have so far in the gesture recognizer
function:
@objc func personDragRecognizer(recognizer: UIPanGestureRecognizer) {
let rotationAngle: CGFloat = 1.6
let translation = recognizer.translation(in: rView)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x, y:view.center.y + translation.y)
view.transform = CGAffineTransform(rotationAngle: rotationAngle)
}
recognizer.setTranslation(CGPoint.zero, in: rView)
if recognizer.view?.center == CGPoint(x: 197.5, y: 232.5) {
PlaygroundPage.current.liveView = eeView
}
The problem with this is that it rotates
to 576º bc
that's 1.6 times 360
. And it doesn't keep on rotating it only does it once. I want it to continually rotate.
If anyone could help the help would be immensely appreciated. Thanks so so much in advance!!
Cheers, Theo
Upvotes: 1
Views: 414
Reputation: 495
I'm not sure if I fully understood the feature you're trying to implement. Here is a sample for UIView subclass responsible for image rotation.
class CustomView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
let panGR = UIPanGestureRecognizer(target: self, action: #selector(panGestureDetected(sender:)))
self.gestureRecognizers = [panGR]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var gestureBeginning: CGFloat = 0.0
func panGestureDetected(sender: UIPanGestureRecognizer) {
guard sender.numberOfTouches > 0 else { return }
let touchPoint = sender.location(ofTouch: 0, in: self)
switch sender.state {
case .began:
gestureBeginning = touchPoint.x
print("gestureBeginning: \(gestureBeginning)")
case .changed:
let progress = touchPoint.x - gestureBeginning
print("progress: \(progress)")
let rotationAngle: CGFloat = 1.6 * progress
let view = self.subviews[0]
let rads = rotationAngle * .pi / 180
view.transform = CGAffineTransform(rotationAngle: rads)
default:
break
}
}
}
To run it on a playground:
let imageView = UIImageView(image: #imageLiteral(resourceName: "image.png"))
imageView.frame = CGRect(origin: CGPoint(x: 50.0, y: 50.0), size: CGSize(width: 150.0, height: 150.0))
let containerView = CustomView(frame: CGRect(origin: .zero, size: CGSize(width: 250.0, height: 250.0)))
containerView.addSubview(imageView)
PlaygroundPage.current.liveView = containerView
PlaygroundPage.current.needsIndefiniteExecution = true
Upvotes: 4