CGImageRef旋转扭曲图像

时间:2015-02-24 17:25:06

标签: objective-c cgaffinetransform image-rotation cgimageref

请使用以下代码进行轮换:

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;

结果我得到了扭曲的图像。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

.
.
.
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
.
.
.

如评论所述,原点位于0.0, 0.0而不是widthheight