LoginSignup
11
15

More than 5 years have passed since last update.

UIImageを合成する(重ねる)Extension

Posted at

UIImageViewを重ねれば済むんだけど、大人の都合で重ねられない時用のメモ

extension UIImage {

    func composite(image: UIImage) -> UIImage? {

        UIGraphicsBeginImageContextWithOptions(self.size, false, 0)
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))

        // 画像を真ん中に重ねる
        let rect = CGRect(x: (self.size.width - image.size.width)/2,
                          y: (self.size.height - image.size.height)/2,
                          width: image.size.width,
                          height: image.size.height)
        image.draw(in: rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
}

引数を配列とかに変えれば何枚でも重ねられるし、rectをいじれば重ねる画像のリサイズもできる。

11
15
0

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
11
15