Implementation of iOS Picture Cutting

  • 2021-11-29 08:40:35
  • OfStack

iOS picture clipping methods, there are two main, 1 to look at.

Cut through CGImage or CIImage

UIImage Have cgImage And ciImage Property, you can get the CGImage And CIImage Object. CGImage And CIImage Objects have cropping(to:) Method, passing in CGRect Indicates the area to clip using the UIImage The coordinates of).


static func cropImage(_ image: UIImage, withRect rect: CGRect) -> UIImage? {
  if let cgImage = image.cgImage,
    let croppedCgImage = cgImage.cropping(to: rect) {
    return UIImage(cgImage: croppedCgImage)
  } else if let ciImage = image.ciImage {
    let croppedCiImage = ciImage.cropping(to: rect)
    return UIImage(ciImage: croppedCiImage)
  }
  return nil
}

Right CGImage For example, the incoming CGRect If the parameter is not in the original area at all, cropping(to:) Method returns null; If there is a part in the original image area, cropping(to:) Method returns the CGImage .

Cropping by bitmap (Bitmap)

You can also get the cropped picture by redrawing the picture with bitmap.


static func cropImage(_ image: UIImage, withRect rect: CGRect) -> UIImage? {
  UIGraphicsBeginImageContext(rect.size)
  guard let context = UIGraphicsGetCurrentContext() else { return nil }
  context.translateBy(x: -rect.minX, y: -rect.minY)
  image.draw(at: .zero)
  let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
  return croppedImage
}

Bitmap size is the area to be cropped CGRect The size of size . Drawing with the original image, in order to make the cropping area just in the bitmap area, coordinate displacement is needed context.translateBy(x: -rect.minX, y: -rect.minY) .

If the incoming CGRect Parameter is partially or completely outside the original area, the part outside the original area will also be drawn (drawn as transparent), which is the same as CGImage The clipping method of is different.

After a few simple attempts, it was found that CPU cropping with CGImage had a lower occupancy rate than cropping with bitmap. The former is recommended for performance only. If you want the cropped picture not to exceed the original image area, it is also recommended to use the former. Use the latter if you need to draw something else (such as other shapes, colors, or something outside the original area).


Related articles: