创建 CFDictionary

Creating a CFDictionary

试图让下面的代码工作:

导入 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: [=10=]) }
}

我需要知道如何正确初始化 CFDictionary。不幸的是,它似乎并不像我预测的那么容易。 我做了一些实验和研究,似乎有相互矛盾的信息。

首先,Apple 文档中有一个关于 kCGImageSourceThumbnailMaxPixelSize 键的条目:

kCGImageSourceThumbnailMaxPixelSize

The maximum width and height in pixels of a thumbnail. If this key is not specified, the width and height of a thumbnail is not limited and thumbnails may be as big as the image itself. If present, this key must be a CFNumber value. This key can be provided in the options dictionary that you pass to the function CGImageSourceCreateThumbnailAtIndex.

在研究了如何初始化 CFNumber 之后,我找到了 CFNumber

的摘录

CFNumber is “toll-free bridged” with its Cocoa Foundation counterpart, NSNumber. This means that the Core Foundation type is interchangeable in function or method calls with the bridged Foundation object

然后我尝试这样做:

let options: CFDictionary = [
    kCGImageSourceThumbnailMaxPixelSize: NSNumber(double: 3.0)
]

并收到错误消息:'_' is not convertible to 'CFString!'Type of expression is ambiguous without more context

这是您的工作代码:

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
            }
        }
    }
}

来自文档:

The implicit conversions from bridged Objective-C classes (NSString/NSArray/NSDictionary) to their corresponding Swift value types (String/Array/Dictionary) have been removed, making the Swift type system simpler and more predictable.

您遇到的问题是 CFStrings,例如 kCGImageSourceThumbnailMaxPixelSize。这些不再自动转换为字符串。

引用自