mercator
mercator

Reputation: 99

Rotate CIImage in Swift 2 using CGAffineTransformMakeRotation

I try and rotate a CIImage in Swift2 using

let rotatedImage        = someCIImage.imageByApplyingTransform(CGAffineTransformMakeRotation(CGFloat(M_PI / 2.0))))

When I look at the sized of the resulting rectangle, it has been rotated. (it was 1000x500 and now is 500x1000). However, the calculations I do subsequently (convert to bitmap and access individual pixels) indicate differently. Am I right that the the above transformation rotates around the center of the image, i.e. in the above example around 500/250?

Upvotes: 2

Views: 3034

Answers (2)

samwize
samwize

Reputation: 27383

In Swift 5, the code gets nicer. This is a CIImage extension method to easily rotate itself around the center.

func rotate(_ angle: CGFloat) -> CIImage {
    let transform = CGAffineTransform(translationX: extent.midX, y: extent.midY)
        .rotated(by: angle)
        .translatedBy(x: -extent.midX, y: -extent.midY)
    return applyingFilter("CIAffineTransform", parameters: [kCIInputTransformKey: transform])
}

Upvotes: 3

Flex Monkey
Flex Monkey

Reputation: 3643

That transform rotates around the image's origin. This version sets the pivot point to the centre:

var tx = CGAffineTransformMakeTranslation(
    image.extent.width / 2,
    image.extent.height / 2)

tx = CGAffineTransformRotate(
    tx,
    CGFloat(M_PI_2))

tx = CGAffineTransformTranslate(
    tx,
    -image.extent.width / 2,
    -image.extent.height / 2)

var transformImage = CIFilter(
    name: "CIAffineTransform",
    withInputParameters: [
        kCIInputImageKey: image,
        kCIInputTransformKey: NSValue(CGAffineTransform: tx)])!.outputImage!

Simon

Upvotes: 7

Related Questions