如何在 uiimage 选择器控制器中更改图像大小

Posted

技术标签:

【中文标题】如何在 uiimage 选择器控制器中更改图像大小【英文标题】:How to change a image size in uiimage picker controller 【发布时间】:2016-12-04 04:28:34 【问题描述】:

以下代码拍摄一张图片并在 uiimageview 上显示。该pitcure填满了整个uiimageview。如何使图像看起来更小,以便保存的图像不是整个屏幕。我希望在拍摄的照片周围有一个边框。一个矩形边框。谢谢。

@IBAction func Camera(_ sender: AnyObject) 

    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)

            func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject: AnyObject]!)
                cameraScreen.image = image
                self.dismiss(animated: true, completion: nil);
                screenView = UIImageView()

                screenView.frame = CGRect(x:0, y: 0, width: self.view.frame.width, height: self.view.frame.height)





                UIGraphicsBeginImageContext(self.cameraScreen.frame.size)
                self.view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)




【问题讨论】:

您想缩放从图像选择器完成处理程序获得的图像吗? 【参考方案1】:

这是您必须在 didFinishPickingImage 完成处理程序中调用的一种方法。

func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage 

  let scale = newWidth / image.size.width
  let newHeight = image.size.height * scale
  UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
  image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
  let newImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()

  return newImage

这个方法会改变图片的大小。

【讨论】:

CGSizeMake 它在 Swift 3 中不可用 如何编写 didFinishPickingImage 完成处理程序?这是准确的 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) if let pickImage = info[UIImagePickerControllerOriginalImage] as? UIImagedismissViewControllerAnimated(true,completion:self.customFunction(pickedImage))elsedismissViewControllerAnimated(true,completion:nil).【参考方案2】:

更新了 Kirti Parghi 对 Swift 3 的回答

func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage? 

    let scale = newWidth / image.size.width
    let newHeight = image.size.height * scale
    UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
    image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage

【讨论】:

以上是关于如何在 uiimage 选择器控制器中更改图像大小的主要内容,如果未能解决你的问题,请参考以下文章

保存 UIImage 中显示的图像并对其进行分类

更改 UIImageView 大小以匹配图像与 AutoLayout

从图像选择器中选择的图像/视频大小(以字节为单位)

如何更改 UITableView 背景图像的大小?

从带有数据的照片库中打开 UIImage

如何在 swift 中单击按钮时更改 uiimage 的图像?