ios - 按角度旋转 UIImageView

标签 ios xcode

我想通过按下按钮来旋转 UIImageView。我正在使用这段代码:

#import "UIImage-Extensions.h"
UIImage *rotatedImage = [SplashItGroupPicker.image imageRotatedByDegrees:360/arrayCount];
SplashItGroupPicker.image = rotatedImage;

在“UIImage-Extensions.h”中我有:

@interface UIImage (CS_Extensions)
- (UIImage *)imageRotatedByRadians:(CGFloat)radians;
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees;

在 .m 中:

- (UIImage *)imageRotatedByRadians:(CGFloat)radians
{
return [self imageRotatedByDegrees:RadiansToDegrees(radians)];
}

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

// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
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, DegreesToRadians(degrees));

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

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

}

...旋转效果很好,但是当图像旋转时,图像也会变小,我不明白为什么。有什么想法吗?

最佳答案

猜测一下,这是否只发生在 Retina 屏幕上?每当从图形上下文中保存 UIImage 时,您需要确保比例正确。我是这样做的:

CGFloat scale = [[UIScreen mainScreen] scale];
CGSize size = CGSizeMake(rotatedViewBox.frame.size.width * scale, rotatedViewBox.frame.size.height * scale);

UIGraphicsBeginImageContext( size );

/* Do your image manipulations here */

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

// overwrite the image with one that has the correct scale set
newImage = [UIImage imageWithCGImage:newImage.CGImage scale:scale orientation:newImage.imageOrientation];

关于ios - 按角度旋转 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13960989/

相关文章:

ios - Xcode 6 设备特定的 Assets 目录

xcode - 从 Xcode 9 构建中缺少所需的图标文件

ios - 归档 xcode 项目

ios - 我无法在 ios8 中将图片上传到亚马逊服务器?

ios - 带 Tableview 的辅助触摸 Laggy

ios - FCM - node.js 中的定时器功能

objective-c - AuthorizationExecuteWithPrivileges 已弃用

ios - 从命令行导入 xcode 方案

ios - 如何在 Firebase DB 中更新子项的特定值

ios - Swift 4 中的核心数据并发问题