Search code examples
swiftswift2cgrectmake

Swift: Why CGImageCreateWithImageInRect() creates a rectangle 1 more pix larger?


When I use CGImageCreateWithImageInRect() to create an CGImage it creates a rectangle 1 px taller and 1 px wider than the rectangle I passed in. Why is this happening?

let rect: CGRect = CGRectMake(CGFloat(124.583333333333), CGFloat(156.416666666667), CGFloat(180.0), CGFloat(180.0))
let imgRef: CGImageRef = CGImageCreateWithImageInRect(img.CGImage, rect)!
print(rect.size)     // 180,180
print(CGImageGetWith(imgRef), CGImageGetHeight(imgRef))  // 181, 181

Solution

  • Your CGRect has a non-whole number origin. CGImageCreateWithImageInRect will use any pixel that the CGRect overlaps (including the partial pixels).