前景图像变小,同时将1个图像叠加在另一个上

时间:2016-06-27 11:12:02

标签: ios swift uiimageview touchesbegan

我正在尝试创建一个应用,用户可以将1张图片拖到另一张图片上,然后可以保存该图片。

我写了以下代码:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var mainImageView: UIImageView!    //Background Image
var Person: UIImageView!         //Foreground Image
var location = CGPoint(x: 0, y: 0)
var image: UIImage!
var frontSize: CGSize!

@IBOutlet weak var overlayButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let image: UIImage = UIImage(named: "pizza")!
    frontSize = image.size
    Person = UIImageView(frame: CGRectMake(90, 140, image.size.width, image.size.height))
    Person.image = image
    Person.contentMode = .ScaleAspectFit

    Person.userInteractionEnabled = true

    self.mainImageView.addSubview(Person)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)


}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "detailImage") {
        let imageVC = (segue.destinationViewController as! ImageViewController)

        imageVC.image = image
    }
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent!) {

    let touch : UITouch! = event.allTouches()?.first

    location = touch.locationInView(self.mainImageView)

    Person.center = location

}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent!) {

    let touch : UITouch! = event.allTouches()?.first

    location = touch.locationInView(self.mainImageView)

    Person.center = location

}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let size = CGSizeMake(mainImageView.image!.size.width, mainImageView.image!.size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)

    mainImageView.image?.drawInRect(CGRectMake(mainImageView.frame.origin.x, mainImageView.frame.origin.y, size.width, size.height))
    Person.image?.drawInRect(CGRectMake(location.x, location.y, frontSize.width, frontSize.height))

    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    //set finalImage to IBOulet UIImageView
    image = newImage

}

}

我在UIButton下面有一个mainImageView然后会执行一个segue,因此,基本上mainImageView的宽度和高度与主屏幕不同。 代码确实有效,只有一点问题。与原始尺寸相比,前景图像(人物)变得非常小,甚至与我拖动它的图像相同。

0 个答案:

没有答案