How to Rotate an Uiimageview by 20 Degrees

How can I rotate an UIImageView by 20 degrees?

A transformation matrix is not incredibly difficult. It's quite simple, if you use the supplied functions:

imgView.transform = CGAffineTransformMakeRotation(.34906585);

(.34906585 is 20 degrees in radians)


Swift 5:

imgView.transform = CGAffineTransform(rotationAngle: .34906585)

How to Rotate a UIImage 90 degrees?

What about something like:

static inline double radians (double degrees) {return degrees * M_PI/180;}
UIImage* rotate(UIImage* src, UIImageOrientation orientation)
{
UIGraphicsBeginImageContext(src.size);

CGContextRef context = UIGraphicsGetCurrentContext();

if (orientation == UIImageOrientationRight) {
CGContextRotateCTM (context, radians(90));
} else if (orientation == UIImageOrientationLeft) {
CGContextRotateCTM (context, radians(-90));
} else if (orientation == UIImageOrientationDown) {
// NOTHING
} else if (orientation == UIImageOrientationUp) {
CGContextRotateCTM (context, radians(90));
}

[src drawAtPoint:CGPointMake(0, 0)];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

How to rotate UIImage

You may rotate UIImageView itself with:

UIImageView *iv = [[UIImageView alloc] initWithImage:image];
iv.transform = CGAffineTransformMakeRotation(M_PI_2);

Or if you really want to change image, you may use code from this answer, it works.

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.

How can I rotate an UIImageView in Interface Builder?

You can't do this in the current version of Xcode. You may submit a feature request to Apple at https://feedbackassistant.apple.com/

However if you want to do it, you will need to write some code

#define RADIANS(degrees) ((degrees * M_PI) / 180.0)

theView.transform = CGAffineTransformRotate(theView.transform, radians)


Related Topics



Leave a reply



Submit