How to Rotate Image in Swift

How to rotate image in Swift?

This is an extension of UIImage that targets Swift 4.0 and can rotate just the image without the need for a UIImageView. Tested successfully that the image was rotated, and not just had its exif data changed.

import UIKit

extension UIImage {
func rotate(radians: CGFloat) -> UIImage {
let rotatedSize = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: CGFloat(radians)))
.integral.size
UIGraphicsBeginImageContext(rotatedSize)
if let context = UIGraphicsGetCurrentContext() {
let origin = CGPoint(x: rotatedSize.width / 2.0,
y: rotatedSize.height / 2.0)
context.translateBy(x: origin.x, y: origin.y)
context.rotate(by: radians)
draw(in: CGRect(x: -origin.y, y: -origin.x,
width: size.width, height: size.height))
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return rotatedImage ?? self
}

return self
}
}

To perform a 180 degree rotation, you can call it like this:

let rotatedImage = image.rotate(radians: .pi)

If for whatever reason it fails to rotate, the original image will then be returned.

Rotate UIImage in swift

This works for me:

works Fine :)

func imageRotatedByDegrees(oldImage: UIImage, deg degrees: CGFloat) -> UIImage {
//Calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox: UIView = UIView(frame: CGRectMake(0, 0, oldImage.size.width, oldImage.size.height))
let t: CGAffineTransform = CGAffineTransformMakeRotation(degrees * CGFloat(M_PI / 180))
rotatedViewBox.transform = t
let rotatedSize: CGSize = rotatedViewBox.frame.size
//Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap: CGContextRef = UIGraphicsGetCurrentContext()!
//Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width / 2, rotatedSize.height / 2)
//Rotate the image context
CGContextRotateCTM(bitmap, (degrees * CGFloat(M_PI / 180)))
//Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0)
CGContextDrawImage(bitmap, CGRectMake(-oldImage.size.width / 2, -oldImage.size.height / 2, oldImage.size.width, oldImage.size.height), oldImage.CGImage)
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}

Swift 3:

func imageRotatedByDegrees(oldImage: UIImage, deg degrees: CGFloat) -> UIImage {
//Calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox: UIView = UIView(frame: CGRect(x: 0, y: 0, width: oldImage.size.width, height: oldImage.size.height))
let t: CGAffineTransform = CGAffineTransform(rotationAngle: degrees * CGFloat.pi / 180)
rotatedViewBox.transform = t
let rotatedSize: CGSize = rotatedViewBox.frame.size
//Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap: CGContext = UIGraphicsGetCurrentContext()!
//Move the origin to the middle of the image so we will rotate and scale around the center.
bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
//Rotate the image context
bitmap.rotate(by: (degrees * CGFloat.pi / 180))
//Now, draw the rotated/scaled image into the context
bitmap.scaleBy(x: 1.0, y: -1.0)
bitmap.draw(oldImage.cgImage!, in: CGRect(x: -oldImage.size.width / 2, y: -oldImage.size.height / 2, width: oldImage.size.width, height: oldImage.size.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}

Swift: Rotating UIImage and filling it

You just need to set a fill color and fill your context before rotating the image:



extension UIImage {
func rotatedBy(degree: CGFloat) -> UIImage? {
guard let cgImage = cgImage else { return nil }
UIGraphicsBeginImageContextWithOptions(size, false, 0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
defer { UIGraphicsEndImageContext() }
UIColor.white.setFill()
context.fill(.init(origin: .zero, size: size))
context.translateBy(x: size.width/2, y: size.height/2)
context.scaleBy(x: 1, y: -1)
context.rotate(by: -degree * .pi / 180)
context.draw(cgImage, in: CGRect(origin: .init(x: -size.width/2, y: -size.height/2), size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
}

Rotate Image 5 degrees each time user clicks button in swift

The code will only rotate the imageView,if the image size changes,you may have missed some code.

func rotate(isForward: Bool) {
self.cropImageView.transform = self.cropImageView.transform.rotated(by: (isForward ? -1 : 1) * .pi * (5.0 / 180.0))
}

How to rotate a image from a specific anchor point

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()

}

Rotate the image by 180 degrees

To rotate an image you could use this snippet:

UIView.animateWithDuration(2, animations: {
self.imageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
})

You can adjust the animation seconds (currently 2).

To set the image back again use the following code:

UIView.animateWithDuration(2, animations: {
self.imageV.transform = CGAffineTransform.identity
})

Swift 4.x version:


Rotate:

UIView.animate(withDuration: 2) {
self.imageView.transform = CGAffineTransform(rotationAngle: .pi)
}

Set the image to it´s normal state:

UIView.animate(withDuration: 2) {
self.imageView.transform = CGAffineTransform.identity
}

How do i keep on rotating an image until a response from a server in swift

This code rotates your UIImageView indefinitely using CABasicAnimation:

let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(.pi * 2.0)
rotateAnimation.duration = 1.0 // Change this to change how many seconds a rotation takes
rotateAnimation.repeatCount = Float.greatestFiniteMagnitude

updateIcon.layer.add(rotateAnimation, forKey: "rotate")

And when you get your signal from your server you can call

updateIcon.layer.removeAnimation(forKey: "rotate")

to stop the animation



Related Topics



Leave a reply



Submit