在图像上绘图会导致照片扩展

时间:2016-01-16 06:27:57

标签: ios iphone swift image draw

您好我在一个应用程序中构建,允许用户使用他们的手指在图像上绘制一条线,我的问题是,当用户触摸屏幕开始绘制图像扩展,使图像成为扭曲。

以下是ViewController的代码:

更新:代码已更新,尝试使用第二张图片视图以及来自MailE的建议

import UIKit
import MobileCoreServices

class NewAutographViewControler: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIGestureRecognizerDelegate {
    
    var signEditMode: Bool = false
    
    @IBOutlet var btnEdit: UIBarButtonItem!
    @IBOutlet var textFieldAlbum: UITextField!

    @IBOutlet var imageView: UIImageView!
    
    @IBOutlet var signImageView: UIImageView!

    @IBAction func btnBackClick(sender: AnyObject) {
        self.navigationController?.popViewControllerAnimated(true)
        
    }
    
    @IBAction func btnEditClick(sender: AnyObject) {
        if signEditMode {
            signEditMode = false
            signImageView.backgroundColor = nil
            btnEdit.title = "Edit"
            signImageView.gestureRecognizers?.removeAll()
        }
        else {
            signEditMode = true
            btnEdit.title = "Done"
            signImageView.backgroundColor = UIColor(white: 1, alpha: 0.5)
            let tap = UIPanGestureRecognizer(target: self, action: Selector("handleTap:"))
            tap.delegate = self
            signImageView.userInteractionEnabled = true
            signImageView.addGestureRecognizer(tap)
        }
    }
    
    func handleTap(sender: UIPanGestureRecognizer? = nil) {
        let recognizer:UIPanGestureRecognizer = sender!
        
        let translation = recognizer.translationInView(self.view)
        if let view = recognizer.view {
            view.center = CGPoint(x:view.center.x + translation.x,
                y:view.center.y + translation.y)
        }
        recognizer.setTranslation(CGPointZero, inView: self.view)
        
    }
    
    func getSaveResponse( response: Bool){
        dispatch_async(dispatch_get_main_queue()) {
        print("getSaveResponse")
        print(response)
        if response {
            let alert = UIAlertController(title: "Save", message:  "Autograph Saved!", preferredStyle: .Alert)
            
            let save = UIAlertAction(title: "New", style: .Default) { (alertAction: UIAlertAction!) ->
                Void in
                self.newPhoto()
            }
            
            let done = UIAlertAction(title: "Done", style: .Default) { (alertAction: UIAlertAction!) ->
                Void in
                self.btnBackClick(self)
            }
            
            alert.addAction(save)
            alert.addAction(done)
            self.presentViewController(alert, animated: true, completion: nil)
            
        }
        else {
            let alert = UIAlertController(title: "Save", message:  "Uh Oh! Autograph could not be save!", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
        }

    }
    
    @IBAction func btnSaveClick(sender: AnyObject) {
        print("save click")
        mergeImages()
        let newPhotoAlbum = PhotoAlbum()
        let validate = newPhotoAlbum.saveImage(imageView.image!, funParam: getSaveResponse)
        if validate == false {
            getSaveResponse(false)
        }
        
    }
    
    //drawing variables
    var lastPoint = CGPoint.zero
    var red: CGFloat = 0.0
    var green: CGFloat = 0.0
    var blue: CGFloat = 0.0
    var brushWidth: CGFloat = 10.0
    var opacity: CGFloat = 1.0
    var swiped = false
    var imageSize: CGSize = CGSize(width: 0,height: 0)
    
    //end-drawing variables
    
    override func viewDidLoad() {
        super.viewDidLoad()
        newPhoto()
        
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func newPhoto() {
        if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = UIImagePickerControllerSourceType.Camera
            //picker.mediaTypes = [kUTTypeImage as String]
            //picker.allowsEditing = true
            self.presentViewController(picker, animated: true, completion: nil)
        }
        else {
            let alertController = UIAlertController(title: "Camera Error", message: "No Camera Detected!", preferredStyle: UIAlertControllerStyle.Alert)
            //alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
            
            let dismiss = UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default) { (alertAction: UIAlertAction!) ->
                Void in
                self.navigationController?.popViewControllerAnimated(true)
            }
            alertController.addAction(dismiss)
            self.presentViewController(alertController, animated: true, completion: nil)
            
            
        }
        
        
        
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
        print("Received image from camera")
        //let mediaType = info[UIImagePickerControllerMediaType] as! String
        var originalImage:UIImage? //, editedImage:UIImage?, imageToSave:UIImage?
        //let compResult:CFComparisonResult = CFStringCompare(mediaType as NSString!, kUTTypeImage, CFStringCompareFlags.CompareCaseInsensitive)
        //if ( compResult == CFComparisonResult.CompareEqualTo ) {
            
            //editedImage = info[UIImagePickerControllerEditedImage] as! UIImage?
            originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage?
            
            /*if ( editedImage != nil ) {
                imageToSave = editedImage
            } else {
                imageToSave = originalImage
            }
            imageView.image = imageToSave
            imageView.reloadInputViews()
        }*/
        imageView.image = originalImage
        picker.dismissViewControllerAnimated(true, completion: nil)
        imageSize = (originalImage?.size)!
        //print(imageView.frame.size)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    //drawing-functions
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if signEditMode {
            return
        }
            swiped = false
            if let touch:UITouch = touches.first! as UITouch {
                //lastPoint = touch.locationInView(self.view)
                lastPoint = touch.locationInView(signImageView)
            }
        
    }
    
    func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {
        
        /*var scale: CGFloat = 1.0;
        if UIScreen.mainScreen().respondsToSelector(Selector("scale")) {
            let tmp: CGFloat = UIScreen.mainScreen().scale
            if (tmp > 1.5) {
                scale = 2.0;
            }
        }
        
        if(scale > 1.5) {
            UIGraphicsBeginImageContextWithOptions(view.frame.size, false, scale);
        } else {
            UIGraphicsBeginImageContext(view.frame.size);
        }
        print(imageView.frame.size)
        */
        
        // 1
        //UIGraphicsBeginImageContext(view.frame.size)
        //UIGraphicsBeginImageContext(self.imageView.frame.size)
        UIGraphicsBeginImageContextWithOptions(self.signImageView.bounds.size, false, 0)
        
        let context = UIGraphicsGetCurrentContext()
        //tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
        //imageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
        signImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: self.signImageView.bounds.size.width, height: self.signImageView.bounds.size.height))
        
        // 2
        CGContextMoveToPoint(context, fromPoint.x, fromPoint.y)
        CGContextAddLineToPoint(context, toPoint.x, toPoint.y)
        
        // 3
        CGContextSetLineCap(context, .Round)
        CGContextSetLineWidth(context, brushWidth)
        CGContextSetRGBStrokeColor(context, red, green, blue, 1.0)
        CGContextSetBlendMode(context, .Normal)
        
        // 4
        CGContextStrokePath(context)
        
        // 5
        //tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        //tempImageView.alpha = opacity
        //imageView.autoresizingMask =  [.FlexibleRightMargin, .FlexibleLeftMargin, .FlexibleBottomMargin, .FlexibleTopMargin]
        //Change from Fit to Fill
        //imageView.contentMode = UIViewContentMode.ScaleAspectFill
        
        signImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
    }
    
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // 6
        swiped = true
        if let touch:UITouch = touches.first! as UITouch {
            //let currentPoint = touch.locationInView(view)
            let currentPoint = touch.locationInView(signImageView)
            drawLineFrom(lastPoint, toPoint: currentPoint)
            
            // 7
            lastPoint = currentPoint
        }

    }
    
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if signEditMode {
            return
        }
        if !swiped {
            // draw a single point
            drawLineFrom(lastPoint, toPoint: lastPoint)
        }
        
        // Merge tempImageView into mainImageView
        /*UIGraphicsBeginImageContext(imageView.frame.size)
        imageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: .Normal, alpha: 1.0)
        imageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: .Normal, alpha: opacity)
        imageView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        tempImageView.image = nil*/
    }
    //end-drawing-functions
    
    //To Merge Sign and Image
    func mergeImages(){
        UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 0)
        imageView.image?.drawInRect(CGRect(x: 0, y: 0, width: imageView.bounds.size.width, height: imageView.bounds.size.height), blendMode: .Normal, alpha: 1.0)
        signImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: imageView.bounds.size.width, height: imageView.bounds.size.height), blendMode: .Normal, alpha: opacity)
        //added contentMode
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        imageView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        signImageView.image = nil
    }
}

请问代码有什么问题?

1 个答案:

答案 0 :(得分:0)

当您的设备支持视网膜或UIScreen.mainScreen()。nativeScale&gt;时,可能会出现问题。 1 尝试
UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, false, 0.0)

而不是
UIGraphicsBeginImageContext(self.imageView.frame.size)