SoFunction
Updated on 2025-04-12

How to implement iOS image cropping

There are two main methods for cropping iOS images, let’s take a look together.

Crop via CGImage or CIImage

UIImagehavecgImageandciImageAttributes, respectivelyCGImageandCIImageObject.CGImageandCIImageAll objectscropping(to:)Method, pass inCGRectThe parameters represent the area to be cropped (usingUIImagecoordinates of ).

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

rightCGImageIn the case, the incomingCGRectIf the parameters are not in the original image area at all,cropping(to:)The method returns empty; if there is a part in the original image area,cropping(to:)Method returns to the original image areaCGImage

Cropping via Bitmap

You can also get the cropped image by redrawing the image through the bitmap.

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

The bitmap size is the area to be croppedCGRectThe size ofsize. Drawing with the original image, in order to make the cropped area exactly in the bitmap area, coordinate displacement is required(x: -, y: -)

If theCGRectSome or all of the parameters are not in the original image area, and the part beyond the original image area will also be drawn (drawn as transparent), which is the same asCGImageThe cutting method is different.

After a few simple attempts, I found that the CPU usage rate of CGImage is lower than that of bitmap cropping. From a performance perspective only, it is recommended to use the former. If you want the cropped image not to exceed the original image area, it is also recommended to use the former. If you need to draw other content (such as other shapes, colors, or the content drawn exceeds the original image area), use the latter.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.