LoginSignup
8
8

More than 5 years have passed since last update.

UIImageViewではなくUIImageを回転させたい

Posted at

UIImageを回転させるためには、どうすればいいのだろう。残念ながらUIImagetransformanimationも持ってないので、UIImageViewを回転させるしかありませんが、生きていればUIImageを回転させるしかないんだって時もあります...orz

そんな時に救ってくれる神の関数がこちら!




    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
    }

使い方


 var pinImage = UIImageView()
        pinImage = UIImageView.init(frame: CGRect.init(x: 0, y:15, width: 200, height: 200))
        let topImage:UIImage = UIImage(named:"pin")!
        pinImage.image = imageRotatedByDegrees(oldImage: topImage, deg: 90.0)
        self.view.addSubview(pinImage)


ソース

github

参考

Rotate UIImage in swift

UIImageViewではなくUIImageを回転させたい

8
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8