ios - 为什么 CGImageCreateWithImageInRect 使用带点的 CGRect 然后使用像素?

标签 ios swift ios8 appledoc

这是关于 CGImageCreateWithImageInRect 的文档.

它以一个 CGRect 对象作为参数。据我了解,CGRect 以

为单位

但是文档说:

"References the pixels within the resulting rectangle, treating the first pixel within the rectangle as the origin of the subimage."

这看起来不准确,并且在我需要调整 UIImages 大小时被证明是这样。我需要将图像尺寸乘以屏幕比例,否则我的图像尺寸不对

var imageRef:CGImageRef = CGImageCreateWithImageInRect(image.CGImage, CGRectMake(0, 0, image.size.width*UIScreen.mainScreen().scale, image.size.height*UIScreen.mainScreen().scale))

如果我不按比例相乘,图像就会太小。

我说这是糟糕的文档(因为它不应该采用以点为单位的 CGRect,然后将其作为像素读取)我说得对吗?还是我不理解这里的一些基本知识?

最佳答案

我认为基于这个测试文档是正确的(像素是像素):

var filename = "InterfaceButtons_Scores@2x.png"
var path = NSBundle.mainBundle().pathForResource(filename,ofType:nil)
var dataProvider = CGDataProviderCreateWithFilename(path!)
var cgimg = CGImageCreateWithPNGDataProvider(dataProvider, nil, false, .RenderingIntentDefault)!

print("size of 100x100px file loaded into CGImage")
print(CGImageGetHeight(cgimg));
print(CGImageGetWidth(cgimg));

var croppedImg = CGImageCreateWithImageInRect(cgimg, CGRect(x: 0, y: 0, width: 100, height: 100))

print("size of CGImage created with 100x100 Rect from 100x100 image")
print(CGImageGetHeight(croppedImg));
print(CGImageGetWidth(croppedImg));


filename = "InterfaceButtons_Scores@1x.png"
path = NSBundle.mainBundle().pathForResource(filename,ofType:nil)
dataProvider = CGDataProviderCreateWithFilename(path!)
cgimg = CGImageCreateWithPNGDataProvider(dataProvider, nil, false, .RenderingIntentDefault)!

print("size of 51x51px file loaded into CGImage")
print(CGImageGetHeight(cgimg));
print(CGImageGetWidth(cgimg));

croppedImg = CGImageCreateWithImageInRect(cgimg, CGRect(x: 0, y: 0, width: 100, height: 100))

print("size of CGImage created with 100x100 Rect from 51x51 image")
print(CGImageGetHeight(croppedImg));
print(CGImageGetWidth(croppedImg));

输出:

size of 100x100px file loaded into CGImage
100
100
size of CGImage created with 100x100 Rect from 100x100 image
100
100
size of 51x51px file loaded into CGImage
51
51
size of CGImage created with 100x100 Rect from 51x51 image
51
51

在不知道您尝试调整大小的确切方式以及您看到的确切结果的情况下,我不确定如何调整您的 UIImage 大小。我知道如果您从 Assets 目录中的 Assets 创建 UIImage(使用 UIImage(named:)),CGImage 属性的实际像素尺寸将取决于设备或模拟器的比例因子。如果同一 Assets 有多种尺寸,UIImage 将加载与系统比例因子匹配的 Assets 。换句话说,在这种情况下,您不能指望 UIImage 的 CGImage 具有一致的尺寸,并且缩放代码可能会出错。

关于ios - 为什么 CGImageCreateWithImageInRect 使用带点的 CGRect 然后使用像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28469202/

相关文章:

ios - 集成 FirebasePhoneAuthUI 进行电话号码身份验证

ios - 如何更新 waitForDuration 常量?

SwiftUI 如何使用 C# 中的 'Delegate-EventHandler-EventArgs' 方式将数据从子级传递到父级

ios8 - 从 native 应用程序到网站的切换不起作用

iphone - 应用商店 : send test account for application validation

ios - 如何在 iOS 上通过 UITextFields 进行枚举

ios - 在 iPad 中显示矢量 map

ios - 如何在 Alamofire 中实现自签名证书?

ios - UIKeyboardWillShowNotification在iOS8中不触发

ios - [cell viewWithTag :] is always returned as nil 中的标签