What I want to do is take a snapshot from my camera , send it to a server and then the server sends me back the image on a viewController. If the image is in portrait mode t
- (UIImage *)rotateImage:(UIImage*)image byDegree:(CGFloat)degrees
{
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,image.size.width, image.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;
[rotatedViewBox release];
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(bitmap, rotatedSize.width, rotatedSize.height);
CGContextRotateCTM(bitmap, DegreesToRadians(degrees));
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-image.size.width, -image.size.height, image.size.width, image.size.height), [image CGImage]);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Swift 4+.
arrowImageView.transform = CGAffineTransform(rotationAngle: .pi/2)
Note: angle is in radian
.pi = 180 degree
.pi/2 = 90 degree
If you want to add with animation
@IBAction func applyTransForm(sender: UIButton) {
sender.isSelected = !sender.isSelected
UIView.animate(withDuration: 1, animations: {
if sender.isSelected {
self.arrowImageView.transform = CGAffineTransform(rotationAngle: .pi)
} else {
self.arrowImageView.transform = CGAffineTransform(rotationAngle: 0)
}
})
}
Output:
Doing it in the Image
Level, in Swift 5:
extension UIImage{
func imageRotated(by radian: CGFloat) -> UIImage{
let rotatedSize = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: radian))
.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: radian)
draw(in: CGRect(x: -origin.y, y: -origin.x,
width: size.width, height: size.height))
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return rotatedImage ?? self
}
return self
}
}
Swift 3 version:
imageView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))
I got an error trying this in XCode 6.3 Swift 1.2
self.imageview.transform = CGAffineTransformMakeRotation(M_PI_2);
You should try this to force type cast fix:
self.imageview.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2));
Swift 4 Edit
imageview.transform = CGAffineTransform(rotationAngle: .pi)
Swift 3 and Swift 4 use .pi instead
eg:
//rotate 90 degrees
myImageView.transform = CGAffineTransform(rotationAngle: .pi / 2)
//rotate 180 degrees
myImageView.transform = CGAffineTransform(rotationAngle: .pi)
//rotate 270 degrees
myImageView.transform = CGAffineTransform(rotationAngle: .pi * 1.5)