旋转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; } 

你的视图的尺寸是错误的,你不想绘制图像的宽度和高度除以2.因为当一个图像旋转它的宽度变成(当提到一个完美的平方)是宽度乘以2倍的平方(2)。 所以如果你的宽度和高度是10,那么你的新宽度(在45度angular)将会在14到15之间…所以你的上下文在一个10×10的区域中绘制一个14×14的图像

你可以通过一些复杂的math来获得使用几何的完美尺寸,或者你可以使用几何来表示| double percentRotated =(弧度%M_PI_4)/ M_PI_4; double newWidth =(percentRotated == 0?img.size.width:img.size.width *(1 +(percentRotated%0.25))); 并为高度做同样的事情,#lazyprogrammer