LoginSignup
6
4

More than 5 years have passed since last update.

画像の合成 Swift3

Last updated at Posted at 2017-07-08

スクリーンショット 2017-07-09 0.35.01.png

スクリーンショット 2017-07-09 0.35.09.png

スクリーンショット 2017-07-09 0.35.20.png

説明

UIGraphicsBeginImageContextWithOptionsからUIGraphicsEndImageContext()の中で画像を合成します。この中で、draw()関数を使って合成する画像を使います。なぜdraw()関数を使えば二枚の画像が合成されるのか中身の仕組みは良くわかりませんが、とにかく下記のように実装することで二つの画像は合成されます。合成された画像はUIGraphicsGetImageFromCurrentImageContext()で受け取ることができます。

実装


import UIKit

class ViewController: UIViewController {

    let imageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()


        let topImage:UIImage = UIImage(named:"topImage")!
        let bottomImage:UIImage = UIImage(named: "bottomImage")!
        let newSize = CGSize(width:bottomImage.size.width, height:bottomImage.size.height)
        UIGraphicsBeginImageContextWithOptions(newSize, false, bottomImage.scale)
        bottomImage.draw(in: CGRect(x:0,y:0,width:newSize.width,height:newSize.height))
        topImage.draw(in: CGRect(x:0,y:0,width:newSize.width,height:newSize.height),blendMode:CGBlendMode.normal, alpha:1.0)
        let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()




        let screenWidth:CGFloat = view.frame.size.width
        let screenHeight:CGFloat = view.frame.size.height
        imageView.image = newImage
        let newRect = CGRect(x:0, y:0, width:200, height:200)
        imageView.frame = newRect
        imageView.center = CGPoint(x:screenWidth/2, y:screenHeight/2)
        self.view.addSubview(imageView)

    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

ソース

github

参考

merge two different images in Swift

don't think twice it's alright

6
4
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
6
4