通过自定义程度旋转UIImage

时间:2014-05-13 13:35:37

标签: ios objective-c uiimage

我使用以下代码来实现此目的。问题是当图像旋转时,它将图像缩放到更接近度数的45'。

当图像设置为90'及其倍数时,图像尺寸没有问题。但是当度数接近45'及其倍数时,图像尺寸会明显缩小。我不想改变图像大小。我该如何处理这个问题?

- (UIImage *)imageRotatedByRadians:(CGFloat)radians img:(UIImage *)img
{
    // calculate the size of the rotated view's containing box for our drawing space
    UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,img.size.width, img.size.height)];
    UIView *nonrotatedViewBox = rotatedViewBox;
    CGAffineTransform t = CGAffineTransformMakeRotation(radians);
    rotatedViewBox.transform = t;
    CGSize rotatedSize = rotatedViewBox.frame.size;

    // Create the bitmap context
    UIGraphicsBeginImageContext(nonrotatedViewBox.frame.size);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();

    // Move the origin to the middle of the image so we will rotate and scale around the center.
    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

    //Rotate the image context
    CGContextRotateCTM(bitmap, radians);

    // Now, draw the rotated/scaled image into the context
    CGContextScaleCTM(bitmap, 1.0, -1.0);
    CGContextDrawImage(bitmap, CGRectMake(-img.size.width / 2, -img.size.height / 2, img.size.width, img.size.height), [img CGImage]);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

1 个答案:

答案 0 :(得分:1)

您的视图尺寸错误,您不想以宽度和高度除以2绘制图像。因为当图像旋转时,它的宽度变为(指的是完美的square)是宽度乘以2倍sqr(2)。所以如果你的宽度和高度都是10,那么你的新宽度(45度角)将在14到15之间...所以你的上下文在10x10区域绘制一个14x14图像

你可以通过一些复杂的数学运算来获得使用几何体的完美尺寸,或者你可以将其展开并说出double percentRotated =(弧度%M_PI_4)/ M_PI_4; double newWidth =(percentRotated == 0?img.size.width:img.size.width *(1 +(percentRotated%0.25)));并为高度做同样的事情,#lazyprogrammer