裁剪UIImage到矩形叠加的形状 - 斯威夫特

时间:2016-04-28 14:49:42

标签: ios iphone swift uiimage uiimagepickercontroller

我对Swift很新。 我打算绘制一个矩形并在矩形叠加中捕获图像。 enter image description here

我在相机上画了一个透明图像。

            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
            imagePicker.mediaTypes = [kUTTypeImage as String]
            imagePicker.allowsEditing = true


            var overlayedImageView: UIImageView = UIImageView(image: UIImage(named: "transparent.png"))
            var cgRect: CGRect = CGRect(x: 200, y: 50, width: 100, height: 400)
            overlayedImageView.frame = cgRect
            imagePicker.cameraOverlayView = overlayedImageView

            self.presentViewController(imagePicker, animated: true,
                completion: nil)

这是我在拍摄图像后所做的事情

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {


    let mediaType = info[UIImagePickerControllerMediaType] as! String

    self.dismissViewControllerAnimated(true, completion: nil)

    if mediaType == (kUTTypeImage as String) {
        let image = info[UIImagePickerControllerOriginalImage]
            as! UIImage

        imageView.image = cropToBoundsNew(image)

        if (newMedia == true) {
            UIImageWriteToSavedPhotosAlbum(image, self,
                "image:didFinishSavingWithError:contextInfo:", nil)
        } else if mediaType == (kUTTypeMovie as String) {
            // Code to support video here
        }

    }
}

我的问题是图像质量下降

    func cropToBoundsNew(image: UIImage) -> UIImage {
    let contextImage: UIImage = UIImage(CGImage: image.CGImage!)
    let contextSize: CGSize = contextImage.size

    let rect: CGRect = CGRectMake(200, 50, 100, 400)

    let imageRef: CGImageRef = CGImageCreateWithImageInRect(contextImage.CGImage, rect)!

    let image: UIImage = UIImage(CGImage: imageRef, scale: image.scale, orientation: image.imageOrientation)

    return image
}

0 个答案:

没有答案