Eugen Software Engineer

How to rotate a UIImage

While I was developing a camera related iOS app I noticed you don’t have swift support to rotate a UIImage, so I wrote a small and useful extension.

Code

import UIKit

extension UIImage {
  public func rotated(byDegrees degrees: CGFloat) -> UIImage? {
    let degreesToRadians: (CGFloat) -> CGFloat = {
      return $0 / 180.0 * CGFloat(M_PI)
    }

    let rotatedViewContainer = UIView(frame: CGRect(origin: .zero, size: size))
    rotatedViewContainer.transform = CGAffineTransform(rotationAngle: degreesToRadians(degrees))
    let rotatedSize = rotatedViewContainer.frame.size
    
    UIGraphicsBeginImageContext(rotatedSize)
    if let bitmap = UIGraphicsGetCurrentContext() {
      bitmap.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0)
      bitmap.rotate(by: degreesToRadians(degrees))
      bitmap.scaleBy(x: 1.0, y: -1.0)
      bitmap.draw(self.cgImage!, in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height))
    }
    let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return rotatedImage
  }
}

Usage

To use it you just need to copy/paste it in your project and you’ll have a new method for every UIImage instance.

Assuming you have the extension in your project, just call .rotated(byDegrees: X) to get the rotated image.

guard let url = URL(string: "https://unsplash.it/300/200"),
  let imageData = try? Data(contentsOf: url),
  let originalImage = UIImage(data: imageData) else {
  fatalError("no image")
}
print(originalImage.size) // (300, 200)

if let rotatedImage = originalImage.rotated(byDegrees: 90) {
  print(rotatedImage.size) // (200, 300)

}

I’ve made the extension available on github: UIImage.rotated and will share it as a cocoapod soon.

Deploy your jekyll site using RSYNC

Jekyll is a static site generator, an open-source tool for creating simple yet powerful websites of all shapes and sizes.

But you already know this, don’t you?

I’m guessing you landed on this page looking for the simplest way to deploy your jekyll powered site to your server.

As you can tell, this website is powered by jekyll also, and I have a simple deploy script that generates your site and copies all the files to your remote server.

#!/bin/sh

jekyll build 
rsync -rchavzP _site/ username@remoteserver:/path/to/remote

Simplest thing ever, and does the job well.

I have it saved in the main directory that’s on git (you are using git right?), named deploy.sh

Make sure you make it executable:

chmod +x deploy.sh

This is how I deploy changes and updates for this site.

I know there are better(read more complex) ways of doing this like using a CI server or a git hook, but I wanted to use the simplest solution for this, I only need the files copied to the remote server.

Hope you found what you were looking for.