【问题标题】:Crop image from bottom programmatically以编程方式从底部裁剪图像
【发布时间】:2017-02-19 15:46:36
【问题描述】:

我正在开发自定义相机应用程序。事情进展顺利。

但是我在从底部裁剪图像时遇到了问题。即裁剪后的图像与原始图像具有完全相同的宽度,但高度将是原始图像的 1/3,并且必须从底部开始。

【问题讨论】:

    标签: ios swift uiimageview crop


    【解决方案1】:

    方法:

    func croppIngimage(ImageCrop:UIImage, toRect rect:CGRect) -> UIImage{
    
        var imageRef:CGImageRef = CGImageCreateWithImageInRect(imageToCrop.CGImage, rect)
        var croppedimage:UIImage = UIImage(CGImage:imageRef)
        return croppedimage
    }
    

    致电:

    var ImageCrop:UIImage  = UIImage(named:"image.png")
    

    【讨论】:

    【解决方案2】:

    Swift 3 解决方案:

    func cropBottomImage(image: UIImage) -> UIImage {
        let height = CGFloat(image.size.height / 3)
        let rect = CGRect(x: 0, y: image.size.height - height, width: image.size.width, height: height)
        return cropImage(image: image, toRect: rect)
    }
    

    使用矩形进行裁剪的辅助方法:

    func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage{
        let imageRef:CGImage = image.cgImage!.cropping(to: rect)!
        let croppedImage:UIImage = UIImage(cgImage:imageRef)
        return croppedImage
    }
    

    【讨论】:

      【解决方案3】:

      这几乎是 Alexburtnik 的回答

      但只是提到 UIImage.size 是逻辑大小(以“点”为单位)

      然而,CGImage.cropping() 使用了实际尺寸(以“像素”为单位)

      因此,如果您使用带有@2x 或@3x 修饰符的图像,您会发现 裁剪实际上是预期的一半或三分之一。

      所以在裁剪时,可以考虑先将矩形乘以图像的“比例”属性,如下所示:

      func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage? {
          var rect = rect
          rect.size.width = rect.width * image.scale
          rect.size.height = rect.height * image.scale
      
          guard let imageRef = image.cgImage?.cropping(to: rect) else {
              return nil
          }
      
          let croppedImage = UIImage(cgImage:imageRef)
          return croppedImage
      }
      

      【讨论】:

        【解决方案4】:

        作为 UIImage 的扩展:

        import UIKit
        
        extension UIImage {
            func crop(to rect: CGRect) -> UIImage? {
                // Modify the rect based on the scale of the image
                var rect = rect
                rect.size.width = rect.size.width * self.scale
                rect.size.height = rect.size.height * self.scale
        
                // Crop the image
                guard let imageRef = self.cgImage?.cropping(to: rect) else {
                    return nil
                }
        
                return UIImage(cgImage: imageRef)
            }
        }
        

        用法:

        let myImage = UIImage(named:"myImage.png")    
        let croppedRect = CGRect(x: 0, y: 0, width: newWidth, height: newHeight)
        let croppedImage = myImage.crop(to: croppedRect)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-03
          • 1970-01-01
          • 2020-06-22
          • 1970-01-01
          • 2013-03-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多