Swift how to crop image with always 1:1 aspect ratio - ios

I am using this library's cropping functions to crop image like Instagram does. (https://github.com/fahidattique55/FAImageCropper) And its cropping part of the code works like this.
private func captureVisibleRect() -> UIImage {
var croprect = CGRect.zero
let xOffset = (scrollView.imageToDisplay?.size.width)! / scrollView.contentSize.width;
let yOffset = (scrollView.imageToDisplay?.size.height)! / scrollView.contentSize.height;
croprect.origin.x = scrollView.contentOffset.x * xOffset;
croprect.origin.y = scrollView.contentOffset.y * yOffset;
let normalizedWidth = (scrollView?.frame.width)! / (scrollView?.contentSize.width)!
let normalizedHeight = (scrollView?.frame.height)! / (scrollView?.contentSize.height)!
croprect.size.width = scrollView.imageToDisplay!.size.width * normalizedWidth
croprect.size.height = scrollView.imageToDisplay!.size.height * normalizedHeight
let toCropImage = scrollView.imageView.image?.fixImageOrientation()
let cr: CGImage? = toCropImage?.cgImage?.cropping(to: croprect)
let cropped = UIImage(cgImage: cr!)
return cropped }
But the problem is for example i have a photo with (800(W)*600(H)) size, and i want to crop it with full width by using full zoom out.This function calculates croprect variable (800(W)*800(H)) correctly. But after this part of the code let cr: CGImage? = toCropImage?.cgImage?.cropping(to: croprect) the cr's resolution becomes (800(W)*600(H)). How can i transform this to square image by filling the empty parts of it with white color?

You can square the image after this process by using the answer in this link. How to draw full UIImage inside a square with white color on the edge
This is the Swift 3 version of it.
private func squareImageFromImage(image: UIImage) -> UIImage{
var maxSize = max(image.size.width,image.size.height)
var squareSize = CGSize.init(width: maxSize, height: maxSize)
var dx = (maxSize - image.size.width) / 2.0
var dy = (maxSize - image.size.height) / 2.0
UIGraphicsBeginImageContext(squareSize)
var rect = CGRect.init(x: 0, y: 0, width: maxSize, height: maxSize)
var context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.white.cgColor)
context?.fill(rect)
rect = rect.insetBy(dx: dx, dy: dy)
image.draw(in: rect, blendMode: CGBlendMode.normal, alpha: 1.0)
var squareImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return squareImage!
}

I suggest you use UIGraphicsContext to draw a rectangle with the intended width and height, filling it with the desired color. Then draw the cropped image on it.
I haven't tested this but this should work for what you want.
I have omitted other parts of your code to focus on the essentials.
....
let context: CGContext? = UIGraphicsGetCurrentContext()
let rect = CGRect(x: 0, y: 0, width: width, height: height)
let color = UIColor.white
color.setFill()
context?.fill(rect)
let cr: CGImage? = toCropImage?.cgImage?.cropping(to: croprect)
let cropped = UIImage(cgImage: cr!)
context?.draw(cropped, in: rect)
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
Replace width and height with the desired width and height.

Simple extensions for Cropping images in different ways
I you want to crop from the center use cropAspectFill and if you want to keep full image and want to make it square then use cropAspectFit
Objective-C solution
#implementation UIImage (crop)
- (UIImage *)cropAspectFill {
CGFloat minSize = MIN(self.size.height, self.size.width);
CGSize squareSize = CGSizeMake(minSize, minSize);
// Get our offset to center the image inside our new square frame
CGFloat dx = (minSize - self.size.width) / 2.0f;
CGFloat dy = (minSize - self.size.height) / 2.0f;
UIGraphicsBeginImageContext(squareSize);
CGRect rect = CGRectMake(0, 0, minSize, minSize);
// Adjust the rect to be centered in our new image
rect = CGRectInset(rect, dx, dy);
[self drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return squareImage;
}
- (UIImage *)cropAspectFit {
// Get a square that the image will fit into
CGFloat maxSize = MIN(self.size.height, self.size.width);
CGSize squareSize = CGSizeMake(maxSize, maxSize);
// Get our offset to center the image inside our new square frame
CGFloat dx = (maxSize - self.size.width) / 2.0f;
CGFloat dy = (maxSize - self.size.height) / 2.0f;
UIGraphicsBeginImageContext(squareSize);
CGRect rect = CGRectMake(0, 0, maxSize, maxSize);
// Adjust the rect to be centered in our new image
rect = CGRectInset(rect, dx, dy);
[self drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return squareImage;
}
#end
Swift solution
extension UIImage {
func cropAspectFill() -> UIImage {
let minSize = min(size.height, size.width)
let squareSize = CGSize(width: minSize, height: minSize)
// Get our offset to center the image inside our new square frame
let dx = (minSize - size.width) / 2.0
let dy = (minSize - size.height) / 2.0
UIGraphicsBeginImageContext(squareSize)
let rect = CGRect(x: 0, y: 0, width: minSize, height: minSize)
// Adjust the rect to be centered in our new image
let centeredRect = rect.insetBy(dx: dx, dy: dy)
draw(in: centeredRect, blendMode: .normal, alpha: 1.0)
let squareImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return squareImage!
}
func cropAspectFit() -> UIImage {
// Get a square that the image will fit into
let maxSize = min(size.height, size.width)
let squareSize = CGSize(width: maxSize, height: maxSize)
// Get our offset to center the image inside our new square frame
let dx = (maxSize - size.width) / 2.0
let dy = (maxSize - size.height) / 2.0
UIGraphicsBeginImageContext(squareSize)
let rect = CGRect(x: 0, y: 0, width: maxSize, height: maxSize)
// Adjust the rect to be centered in our new image
let centeredRect = rect.insetBy(dx: dx, dy: dy)
draw(in: centeredRect, blendMode: .normal, alpha: 1.0)
let squareImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return squareImage!
}
}

Related

how to get the rect of an image to crop it

I am building a app where you can crop multiple images. I am using this code directly from apple:
func cropImage(_ inputImage: UIImage, toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage?
{
let imageViewScale = max(inputImage.size.width / viewWidth,
inputImage.size.height / viewHeight)
// Scale cropRect to handle images larger than shown-on-screen size
let cropZone = CGRect(x:cropRect.origin.x * imageViewScale,
y:cropRect.origin.y * imageViewScale,
width:cropRect.size.width * imageViewScale,
height:cropRect.size.height * imageViewScale)
// Perform cropping in Core Graphics
guard let cutImageRef: CGImage = inputImage.cgImage?.cropping(to:cropZone)
else {
return nil
}
// Return image to UIImage
let croppedImage: UIImage = UIImage(cgImage: cutImageRef)
return croppedImage
}
to crop the image I need a cropRect. I found also a solution in the Internet that I implemented in my code:
func realImageRect() -> CGRect {
let imageViewSize = self.frame.size
let imgSize = self.image?.size
guard let imageSize = imgSize else {
return CGRect.zero
}
let scaleWidth = imageViewSize.width / imageSize.width
let scaleHeight = imageViewSize.height / imageSize.height
let aspect = fmin(scaleWidth, scaleHeight)
var imageRect = CGRect(x: 0, y: 0, width: imageSize.width * aspect, height: imageSize.height * aspect)
// Center image
imageRect.origin.x = (imageViewSize.width - imageRect.size.width) / 2
imageRect.origin.y = (imageViewSize.height - imageRect.size.height) / 2
// Add imageView offset
imageRect.origin.x += self.frame.origin.x
imageRect.origin.y += self.frame.origin.y
return imageRect
}
As I already said, the app can crop multiple images. The images are stored in a array. I also have a crop view, which you can drag around the image with a pan gesture
for i in 0..<imageContentView.count {
let cropRect = CGRect(x: croppedViewArray[i].frame.origin.x - imageContentView[i].realImageRect().origin.x, y: croppedViewArray[i].frame.origin.y - imageContentView[i].realImageRect().origin.y, width: croppedViewArray[i].frame.width, height: croppedViewArray[i].frame.height)
print("cropRect", cropRect)
let croppedImage = ImageCrophandler.sharedInstance.cropImage(imageContentView[i].image!, toRect: cropRect, viewWidth: imageContentView[i].frame.width, viewHeight: imageContentView[i].frame.height)
print("cheight", croppedImage!.size.height,"cwidth", croppedImage!.size.width)
arrayOfCropedImages.append(croppedImage!)
}
The problem what I have is, that every cropped image has a different height and widths, but the images should be all the same size.
I figured out that the size gets calculated on which position the crop view is located.

Resizing the image to Aspect Fit

I am trying to resize images using the following popular code and it is resizing the image but it is resizing the image as Scale to Fill, I would like to resize them as Aspect Fit. How do I do that?
func resizeImage(image: UIImage, newSize: CGSize) -> (UIImage) {
let newRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral
UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
let context = UIGraphicsGetCurrentContext()
// Set the quality level to use when rescaling
context!.interpolationQuality = CGInterpolationQuality.default
let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: newSize.height )
context!.concatenate(flipVertical)
// Draw into the context; this scales the image
context?.draw(image.cgImage!, in: CGRect(x: 0.0,y: 0.0, width: newRect.width, height: newRect.height))
let newImageRef = context!.makeImage()! as CGImage
let newImage = UIImage(cgImage: newImageRef)
// Get the resized image from the context and a UIImage
UIGraphicsEndImageContext()
return newImage
}
I have already set the content mode of image to Aspect Fit but still it is not working.
This is how I called the above code in my collection view controller
cell.imageView.image = UIImage(named: dogImages[indexPath.row])?.resizeImage(image: UIImage(named: dogImages[indexPath.row])
I manually selected my image in storyboard and set its content mode to apsect fit
Did you tried setting the newSize in aspect ratio of original Image size. If you want width fix calculate the height as per width and if you want height fix then calculate width as per height
Calculate height when width is fix:
let fixedWidth: CGFloat = 200
let newHeight = fixedWidth * image.size.height / image.size.width
let convertedImage = resizeImage(image: image, newSize: CGSize(width: fixedWidth, height: newHeight))
Calculate width when height is fix:
let fixedheight: CGFloat = 200
let newWidth = fixedheight * image.size.width / image.size.height
let convertedImage = resizeImage(image: image, newSize: CGSize(width: newWidth, height: fixedheight))
You can use this resized image with aspect fit ratio.
also check the answer: https://stackoverflow.com/a/8858464/2677551, that may help
func scaleImageAspectFit(newSize: CGSize) -> UIImage? {
var scaledImageRect: CGRect = CGRect.zero
let aspectWidth: CGFloat = newSize.width / size.width
let aspectHeight: CGFloat = newSize.height / size.height
let aspectRatio: CGFloat = min(aspectWidth, aspectHeight)
scaledImageRect.size.width = size.width * aspectRatio
scaledImageRect.size.height = size.height * aspectRatio
scaledImageRect.origin.x = (newSize.width - scaledImageRect.size.width) / 2.0
scaledImageRect.origin.y = (newSize.height - scaledImageRect.size.height) / 2.0
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
if UIGraphicsGetCurrentContext() != nil {
draw(in: scaledImageRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
return nil
}
Usage :
let resizedImage = oldImage.scaleImageAspectFit(newSize: CGSize(width: nexSize.width, height: nexSize.height))

Resize an image with drawInRect while maintaining the aspect ratio like Scale Aspect Fill?

I would like to resize an image with drawInRect method, but I would also like to maintain the right aspect ratio, while filling completely the given frame (as .ScaleAspectFill does for UIViewContentMode).
Anyone has a ready answer for this?
Here is my code (pretty straightforward...):
func scaled100Image() -> UIImage {
let newSize = CGSize(width: 100, height: 100)
UIGraphicsBeginImageContext(newSize)
self.pictures[0].drawInRect(CGRect(x: 0, y: 0, width: 100, height: 100))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
OK, so no ready-made answer... I wrote a swift extension for UIImage, feel free to use it if you need it.
Here it is:
extension UIImage {
func drawInRectAspectFill(rect: CGRect) {
let targetSize = rect.size
if targetSize == .zero {
self.draw(in: rect)
}
let widthRatio = targetSize.width / self.size.width
let heightRatio = targetSize.height / self.size.height
let scalingFactor = max(widthRatio, heightRatio)
let newSize = CGSize(width: self.size.width * scalingFactor,
height: self.size.height * scalingFactor)
UIGraphicsBeginImageContext(targetSize)
let origin = CGPoint(x: (targetSize.width - newSize.width) / 2,
y: (targetSize.height - newSize.height) / 2)
self.draw(in: CGRect(origin: origin, size: newSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
scaledImage?.draw(in: rect)
}
}
So in the example above, you use it like that:
self.pictures[0].drawInRectAspectFill(CGRect(x: 0, y: 0, width: 100, height: 100))
The Objective-C version, if someone need it(Paste this code inside a UIIMage category):
- (void) drawInRectAspectFill:(CGRect) recto {
CGSize targetSize = recto.size;
if (targetSize.width <= CGSizeZero.width && targetSize.height <= CGSizeZero.height ) {
return [self drawInRect:recto];
}
float widthRatio = targetSize.width / self.size.width;
float heightRatio = targetSize.height / self.size.height;
float scalingFactor = fmax(widthRatio, heightRatio);
CGSize newSize = CGSizeMake(self.size.width * scalingFactor, self.size.height * scalingFactor);
UIGraphicsBeginImageContext(targetSize);
CGPoint origin = CGPointMake((targetSize.width-newSize.width)/2,(targetSize.height - newSize.height) / 2);
[self drawInRect:CGRectMake(origin.x, origin.y, newSize.width, newSize.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[scaledImage drawInRect:recto];
}

Add transparent space around a UIImage

Lets say we have an image of 600X400 pixel and we want to end up with an new image of 1000x1000 pixel which contains the initial image in the centre and transparent space around it. How can I achieve that in code?
In Swift you can write an extension to UIImage that draws image with insets around it.
Swift 3:
import UIKit
extension UIImage {
func imageWithInsets(insets: UIEdgeInsets) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: self.size.width + insets.left + insets.right,
height: self.size.height + insets.top + insets.bottom), false, self.scale)
let _ = UIGraphicsGetCurrentContext()
let origin = CGPoint(x: insets.left, y: insets.top)
self.draw(at: origin)
let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithInsets
}
}
OLD ANSWER:
import UIKit
extension UIImage {
func imageWithInsets(insets: UIEdgeInsets) -> UIImage {
UIGraphicsBeginImageContextWithOptions(
CGSizeMake(self.size.width + insets.left + insets.right,
self.size.height + insets.top + insets.bottom), false, self.scale)
let context = UIGraphicsGetCurrentContext()
let origin = CGPoint(x: insets.left, y: insets.top)
self.drawAtPoint(origin)
let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithInsets
}
}
This is the solution in Swift 4 inspired by DrummerB answer:
import UIKit
extension UIImage {
func addImagePadding(x: CGFloat, y: CGFloat) -> UIImage? {
let width: CGFloat = size.width + x
let height: CGFloat = size.height + y
UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 0)
let origin: CGPoint = CGPoint(x: (width - size.width) / 2, y: (height - size.height) / 2)
draw(at: origin)
let imageWithPadding = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithPadding
}
}
How to apply:
let image = UIImage(named: "your-image")!
let imageView = UIImageView(image: image.addImagePadding(x: 50, y: 50))
imageView.backgroundColor = UIColor.gray
view.addSubview(imageView)
Features:
Simply pass padding values via parameters
Colored padding (by setting the UIGraphicsBeginImageContextWithOptions opaque parameter to false)
You create a new image context that is 1000x1000, draw your old image in the middle, then get the new UIImage from the context.
// Setup a new context with the correct size
CGFloat width = 1000;
CGFloat height = 1000;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
// Now we can draw anything we want into this new context.
CGPoint origin = CGPointMake((width - oldImage.size.width) / 2.0f,
(height - oldImage.size.height) / 2.0f);
[oldImage drawAtPoint:origin];
// Clean up and get the new image.
UIGraphicsPopContext();
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
A fix for appsunited's answer with better naming convension. To not confuse it the function is mutating or not:
extension UIImage {
func withPadding(_ padding: CGFloat) -> UIImage? {
return withPadding(x: padding, y: padding)
}
func withPadding(x: CGFloat, y: CGFloat) -> UIImage? {
let newWidth = size.width + 2 * x
let newHeight = size.height + 2 * y
let newSize = CGSize(width: newWidth, height: newHeight)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
let origin = CGPoint(x: (newWidth - size.width) / 2, y: (newHeight - size.height) / 2)
draw(at: origin)
let imageWithPadding = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithPadding
}
}
Make a category on UIImage and try this:
+ (UIImage *)imageWithInsets:(CGRect)insetRect image:(UIImage *)image {
CGRect newRect = CGRectMake(0.0, 0.0, insetRect.origin.x+insetRect.size.width+image.size.width, insetRect.origin.y+insetRect.size.height+image.size.height);
// Setup a new context with the correct size
UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
// Now we can draw anything we want into this new context.
CGPoint origin = CGPointMake(insetRect.origin.x, insetRect.origin.y);
[image drawAtPoint:origin];
// Clean up and get the new image.
UIGraphicsPopContext();
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

How Can I Rotate A UIImage and Image Data By 90 Degrees

I have a UIImageView that contains an image. At the minute the user can click to save the image within the UIImageView to disk.
I would like to make it so that the the user can click to rotate the UIImageView and also rotate the UImage within the view so that when the image is saved it keeps the new rotation.
At the minute I have
- (IBAction)rotateImage:(id)sender {
float degrees = 90; //the value in degrees
self.imagePreview.transform = CGAffineTransformMakeRotation(degrees * M_PI/180);
}
Can someone point me in the right direction regarding keeping the current rotation.
Thanks
I have such code in my old app. But this code can be simplified because you have no need to rotate it on non-90 degrees angle.
Objective-C
#implementation UIImage (Rotation)
- (UIImage *)imageRotatedOnDegrees:(CGFloat)degrees
{
// Follow ing code can only rotate images on 90, 180, 270.. degrees.
CGFloat roundedDegrees = (CGFloat)(round(degrees / 90.0) * 90.0);
BOOL sameOrientationType = ((NSInteger)roundedDegrees) % 180 == 0;
CGFloat radians = M_PI * roundedDegrees / 180.0;
CGSize newSize = sameOrientationType ? self.size : CGSizeMake(self.size.height, self.size.width);
UIGraphicsBeginImageContext(newSize);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGImageRef cgImage = self.CGImage;
if (ctx == NULL || cgImage == NULL) {
UIGraphicsEndImageContext();
return self;
}
CGContextTranslateCTM(ctx, newSize.width / 2.0, newSize.height / 2.0);
CGContextRotateCTM(ctx, radians);
CGContextScaleCTM(ctx, 1, -1);
CGPoint origin = CGPointMake(-(self.size.width / 2.0), -(self.size.height / 2.0));
CGRect rect = CGRectZero;
rect.origin = origin;
rect.size = self.size;
CGContextDrawImage(ctx, rect, cgImage);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image ?: self;
}
#end
Swift
extension UIImage {
func imageRotated(on degrees: CGFloat) -> UIImage {
// Following code can only rotate images on 90, 180, 270.. degrees.
let degrees = round(degrees / 90) * 90
let sameOrientationType = Int(degrees) % 180 == 0
let radians = CGFloat.pi * degrees / CGFloat(180)
let newSize = sameOrientationType ? size : CGSize(width: size.height, height: size.width)
UIGraphicsBeginImageContext(newSize)
defer {
UIGraphicsEndImageContext()
}
guard let ctx = UIGraphicsGetCurrentContext(), let cgImage = cgImage else {
return self
}
ctx.translateBy(x: newSize.width / 2, y: newSize.height / 2)
ctx.rotate(by: radians)
ctx.scaleBy(x: 1, y: -1)
let origin = CGPoint(x: -(size.width / 2), y: -(size.height / 2))
let rect = CGRect(origin: origin, size: size)
ctx.draw(cgImage, in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image ?? self
}
}
This will rotate an image by any given radians.
Note this works 2x and 3x retina as well
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees {
CGFloat radians = DegreesToRadians(degrees);
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0, self.size.width, self.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(radians);
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;
UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, [[UIScreen mainScreen] scale]);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(bitmap, rotatedSize.width / 2, rotatedSize.height / 2);
CGContextRotateCTM(bitmap, radians);
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2 , self.size.width, self.size.height), self.CGImage );
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
In Swift 4
imageView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2))
The highlighted state of a UIButton did not take the correct orientation of the normal inserted turned image. So I had to redraw the image like #RyanG showed. Here is the Swift 2.2 code for that:
extension UIImage
{
/// Rotate an image by any given radians.
/// Works for 2x and 3x retina as well.
func imageRotatedByDegrees(degrees: Double) -> UIImage
{
let radians = CGFloat(degrees * (M_PI / 180.0))
let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: self.size))
let t: CGAffineTransform = CGAffineTransformMakeRotation(radians)
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
UIGraphicsBeginImageContextWithOptions(rotatedSize, false, self.scale)
let bitmap = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(bitmap, rotatedSize.width / 2, rotatedSize.height / 2)
CGContextRotateCTM(bitmap, radians)
CGContextScaleCTM(bitmap, 1.0, -1.0)
CGContextDrawImage(bitmap, CGRect(origin: CGPoint(x: -self.size.width / 2, y: -self.size.height / 2), size: self.size), self.CGImage)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
Swift version made from answer of #RyanG with some fixes:
func rotated(by degrees: CGFloat) -> UIImage {
let radians : CGFloat = degrees * CGFloat(.pi / 180.0)
let rotatedViewBox = UIView(frame: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
let t = CGAffineTransform(rotationAngle: radians)
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
UIGraphicsBeginImageContextWithOptions(rotatedSize, false, self.scale)
defer { UIGraphicsEndImageContext() }
guard let bitmap = UIGraphicsGetCurrentContext(), let cgImage = self.cgImage else {
return self
}
bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
bitmap.rotate(by: radians)
bitmap.scaleBy(x: 1.0, y: -1.0)
bitmap.draw(cgImage, in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else {
return self
}
return newImage
}
self.imageview.transform = CGAffineTransformMakeRotation(M_PI/2);

Resources