iiFreeman
iiFreeman

Reputation: 5175

CGImageRef rotation distorted image

Have following code for rotation:

CGFloat angleInRadians = angle * M_PI/180.0;
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);

    CGRect imgRect = CGRectMake(width, height, width, height);
    CGAffineTransform transform = CGAffineTransformMakeRotation(angleInRadians);
    CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, transform);

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef bmContext = CGBitmapContextCreate(NULL,
                                                   rotatedRect.size.width,
                                                   rotatedRect.size.height,
                                                   8,
                                                   0,
                                                   colorSpace,
                                                   (CGBitmapInfo)kCGImageAlphaPremultipliedFirst);
    CGContextSetAllowsAntialiasing(bmContext, true);
    CGContextSetShouldAntialias(bmContext, true);
    CGContextSetInterpolationQuality(bmContext, kCGInterpolationHigh);
    CGColorSpaceRelease(colorSpace);
    CGContextTranslateCTM(
                          bmContext,
                          +(rotatedRect.size.width/2),
                          +(rotatedRect.size.height/2));
    CGContextRotateCTM(bmContext, angleInRadians);
    CGContextTranslateCTM(
                          bmContext,
                          -(rotatedRect.size.width/2),
                          -(rotatedRect.size.height/2));
    CGContextDrawImage(bmContext, CGRectMake(0, 0, rotatedRect.size.width, rotatedRect.size.height), imgRef);

    CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
    return rotatedImage;

As a result I getting distorted image. What I'm doing wrong here?

Upvotes: 0

Views: 163

Answers (1)

geowar
geowar

Reputation: 4447

.
.
.
CGRect imgRect = CGRectMake(0., 0., width, height); // origin at {0, 0}; not {width, height}
.
.
.
CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
CGImageRelease(bmContext);  // don't need this anymore
.
.
.

As commented, the origin is at 0.0, 0.0 not at width or height.

Upvotes: 1

Related Questions