ios - 尝试将我的 UIImage 裁剪为 1 :1 aspect ratio (square) but it keeps enlarging the image causing it to be blurry. 为什么?

标签 ios objective-c uiimageview uiimage cgimage

给定一个 UIImage,我试图将它变成一个正方形。只需切掉一些最大的尺寸,使其纵横比为 1:1。

UIImage *pic = [UIImage imageNamed:@"pic"];
CGFloat originalWidth = pic.size.width;
CGFloat originalHeight = pic.size.height;

float smallestDimension = fminf(originalWidth, originalHeight);

CGRect square = CGRectMake(0, 0, smallestDimension, smallestDimension);
CGImageRef imageRef = CGImageCreateWithImageInRect([pic CGImage], square);

UIImage *squareImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

UIImageView *imageView = [[UIImageView alloc] initWithImage:squareImage];
imageView.frame = CGRectMake(100, 100, imageView.bounds.size.width, imageView.bounds.size.height);

[self.view addSubview:imageView];

但这就是它的结果:

enter image description here

当它应该看起来像这样,但稍微窄一点。

enter image description here

这是为什么?图片为 pic(150x114)/pic@2x(300x228)。

最佳答案

问题是您混淆了逻辑大小和像素大小。在非 Retina 设备上,这两个是相同的,但在 Retina 设备上(如您的情况),像素大小实际上是逻辑大小的两倍。

通常,在设计 GUI 时,您总是可以考虑逻辑大小和坐标,iOS(或 OS X)会确保一切在视网膜屏幕上都翻倍。但是,在某些情况下,尤其是在您自己创建图像时,您必须明确指定您所指的尺寸。

UIImagesize 方法返回逻辑大小。例如,这是非视网膜屏幕上的分辨率。这就是为什么 CGImageCreateWithImageInRect 只会从图像的左上半部分创建一个新图像。

将您的逻辑大小乘以图像的比例(非视网膜设备上为 1,视网膜设备上为 2):

CGFloat originalWidth = pic.size.width * pic.scale;
CGFloat originalHeight = pic.size.height * pic.scale;

这将确保新图像是从原始图像的完整高度(或宽度)创建的。现在,剩下的一个问题是,当您使用

创建一个新的 UIImage
UIImage *squareImage = [UIImage imageWithCGImage:imageRef];

iOS 会认为,这是一张普通的非视网膜图像,它会显示为您预期的两倍大。要解决此问题,您必须在创建 UIImage 时指定比例:

UIImage *squareImage = [UIImage imageWithCGImage:imageRef 
                                           scale:pic.scale 
                                     orientation:pic.imageOrientation];

关于ios - 尝试将我的 UIImage 裁剪为 1 :1 aspect ratio (square) but it keeps enlarging the image causing it to be blurry. 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20429420/

相关文章:

ios - 我可以为 Xcode 9.4.1 安装哪个 Firebase 版本

iphone - iOS 上的 http GET

ios - 使用 animatedImageWithImages 创建的 UIImage 有错误?

IOS-垂直向上移动多个图像

iphone - UIImageView边框问题

ios - 为什么不能通过使用另一个 viewController 来设置 viewController 的变量值?

ios - 滚动或重新加载表格 View 后查看位置变化

ios - 如何显示x轴标题?

c++ - 未在此范围内声明 msgStore (XCode)

objective-c - 阻止我的 iOS 8 iPad 操作表忽略它的父 ViewController?