0

I am trying to draw a "zoomed-in" portion of UIImage and can't find a way to do that...

Say I have an image sized 1000x1000, and I zoom-in to the top left (x:0, y:0 width: 500, height: 500), and I want to draw that portion into another 1000x1000 image.

I am using UIGraphicsImageRenderer but UIImage draw method doesn't accept any source rect, only destination rect (and it draws the entire image).

I was able to achieve what I want by specifying a larger rect in the draw method, but that crashes when the zoom-in level is big (out-of-memory).

This is what I tried:

let srcImg: UIImage = {some UIImage sized 1000x1000}
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 1000, height: 1000))
let scaled = renderer.image { ctx in
    srcImg.draw(in: CGRect(origin: CGPoint.zero, size: CGSize(width: 2000, height: 2000)))
}

Basically I am trying to achieve something like the drawImage API of HTML5 canvas, which gets both src and dst rectangles...

Thanks.

ValYouW
  • 669
  • 2
  • 9
  • 20

1 Answers1

0

Use the UIImage extension from this answer: https://stackoverflow.com/a/28513086/6257435

If I understand your question correctly -- you want to clip the top-left 500x500 pixels from a 1000x1000 image, and scale that up to 1000x1000 -- here is a simple example using that extension:

    if let img1000x1000 = UIImage(named: "img1000x1000") {
        if let topLeft500x500 = img1000x1000.cropped(to: CGRect(x: 0, y: 0, width: 500, height: 500)) {
            if let new1000x1000 = topLeft500x500.filled(to: CGSize(width: 1000, height: 1000)) {
                // do something with new 1000x1000 image
                print()
            }
        }
    }
DonMag
  • 69,424
  • 5
  • 50
  • 86