Swift 3.0: How to call CGImageCreateWithImageInRect()?
Asked Answered
Y

2

17

I need to implement this Objective-C code in Swift 3.0 (I'm using Xcode 8 Beta 3):

// Note: this code comes from an Obj-C category on UIImage
CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, cropRect);
UIImage *image = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];

I can't find anything in the latest documentation for CGImageCreateWithImageInRect().

Yugoslav answered 25/7, 2016 at 12:50 Comment(0)
H
40

When I write this code in Xcode8's Swift editor:

let imageRef = CGImageCreateWithImageInRect(self.CGImage!, cropRect)

Swift has shown me an error as:

error: 'CGImageCreateWithImageInRect' has been replaced by instance method 'CGImage.cropping(to:)'

So, I changed the line to:

let imageRef = self.cgImage!.cropping(to: cropRect)

And the second line of your code seems to be directly convertible to Swift:

let image = UIImage(cgImage: imageRef!, scale: self.scale, orientation: self.imageOrientation)

And the latest documentations of CGImageCreateWithImageInRect,

CGImageCreateWithImageInRect

Clicking the Swift link, it shows:

func cropping(to rect: CGRect) -> CGImage?
Hooligan answered 25/7, 2016 at 13:9 Comment(0)
S
1
var imageRef = self.image.cropping(to: cropRect)
Suzan answered 25/7, 2016 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.