Search code examples
iosswiftuigraphicscontext

Why is there a white edge when cropping an image with UIGraphicsContext?


I am cropping an image with:

UIGraphicsBeginImageContext(croppingRect.size)
let context = UIGraphicsGetCurrentContext()

context?.clip(to: CGRect(x: 0, y: 0, width: rect.width, height: rect.height))        
image.draw(at: CGPoint(x: -rect.origin.x, y: -rect.origin.y))

let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

The cropped image sometimes has a 1px white edge on the right and bottom border. The right bottom corner zoomed in to see the individual pixels looks like this. Apparently the border is not plain white but shades of white which may come from later compression.

enter image description here

Where does this white edge artifact come from?


Solution

  • The issue was that the values of the croppingRect were not full pixels.

    As the values for x, y, width, height where calculated CGFloat numbers the results would sometimes be fractional numbers (e.g. 1.3 instead of 1.0). The solution was to round these values:

    let cropRect = CGRect(
       x: x.rounded(.towardZero), 
       y: y.rounded(.towardZero),
       width: width.rounded(.towardZero),
       height: height.rounded(.towardZero))
    

    The rounding has to be .towardZero (see here what it means) because the cropping rectangle should (usually) not be larger than the image rect.