为了使以下代码正常工作:
导入ImageIO
if let imageSource = CGImageSourceCreateWithURL(self.URL, nil) {
let options: CFDictionary = [
kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height) / 2.0,
kCGImageSourceCreateThumbnailFromImageIfAbsent: true
]
let scaledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options).flatMap { UIImage(CGImage: $0) }
}我需要知道如何正确初始化CFDictionary。不幸的是,这似乎不像我预测的那么容易。我做了一些实验和研究,似乎有相互矛盾的信息。
首先,在Apple中有一个关于kCGImageSourceThumbnailMaxPixelSize键的条目:
kCGImageSourceThumbnailMaxPixelSize 缩略图的最大宽度和高度,以像素为单位。如果未指定此键,则缩略图的宽度和高度不受限制,缩略图可能与图像本身一样大。如果存在,则此键必须是CFNumber值。此键可以在传递给函数CGImageSourceCreateThumbnailAtIndex的选项字典中提供。
在研究了如何初始化CFNumber之后,我找到了CFNumber的摘录
CFNumber与可可基金会的对应方NSNumber是“免费搭桥”的。这意味着核心基础类型在函数或方法调用中与桥接的Foundation对象是可互换的
然后我试着这样做:
let options: CFDictionary = [
kCGImageSourceThumbnailMaxPixelSize: NSNumber(double: 3.0)
]并受到错误消息的欢迎:'_' is not convertible to 'CFString!'和Type of expression is ambiguous without more context。
发布于 2015-08-14 06:44:00
这是您的工作代码:
func processImage(jpgImagePath: String, thumbSize: CGSize) {
if let path = NSBundle.mainBundle().pathForResource(jpgImagePath, ofType: "") {
if let imageURL = NSURL(fileURLWithPath: path) {
if let imageSource = CGImageSourceCreateWithURL(imageURL, nil) {
let maxSize = max(thumbSize.width, thumbSize.height) / 2.0
let options : [NSString : AnyObject] = [
kCGImageSourceThumbnailMaxPixelSize: maxSize,
kCGImageSourceCreateThumbnailFromImageIfAbsent: true
]
let scaledImage = UIImage(CGImage: CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options))
// do other stuff
}
}
}
}来自Docs:
从桥接的Objective类(NSString/NSArray/ and )到相应的Swift值类型(String/Array/Dictionary)的隐式转换已经被删除,使Swift类型系统更简单、更可预测。
在您的例子中,问题是类似于CFStrings的kCGImageSourceThumbnailMaxPixelSize。这些不再自动转换为字符串。
来自HERE的参考。
https://stackoverflow.com/questions/32003809
复制相似问题