DKImagePickerController
描述
DKImagePickerController
是一个高度可定制的纯 Swift 库。
特性
- 支持单选和多选。
- 支持按类型过滤相册和排序。
- 支持横屏、iPad 和方向切换。
- 支持 iCloud。
- 支持批量导出
PHAsset
至本地文件。 - 支持内联模式。
- 可自定义
UICollectionViewLayout
。 - 可自定义
相机
,相册
和照片编辑器
。 - 支持暗黑模式
需求
- iOS 9.0以上(从4.3.0版本开始,不再支持iOS 8)
- 自动引用计数(ARC)
- Swift 4 & 5
安装
CocoaPods
iOS 9及以上版本
DKImagePickerController 已在 CocoaPods 上提供。只需将以下行添加到您的 Podfile 中即可
# For latest release in cocoapods
pod 'DKImagePickerController'
Swift 4.1版本使用
pod 'DKImagePickerController', :git => 'https://github.com/zhangao0086/DKImagePickerController.git', :branch => 'Swift4'
iOS 8版本使用
pod 'DKImagePickerController', :git => 'https://github.com/zhangao0086/DKImagePickerController.git', :branch => 'iOS8'
子规格
目前有7个子规格可用
子规格 | 描述 |
---|---|
核心 | 必需。 |
ImageDataManager | 必需。该子规格为DKImagePickerController 提供数据。 |
资源 | 必需。该子规格提供资源管理和国际化。 |
PhotoGallery | 可选。该子规格为PHAsset提供预览功能。 |
Camera | 可选。该子规格提供相机功能。 |
InlineCamera | 可选。该子规格应由UINavigationController 推送,类似于具有UIImagePickerControllerSourceType.camera 的UIImagePickerController 。 |
PhotoEditor | 可选。该子规格提供基本图像编辑功能。 |
这意味着您只能安装DKImagePickerController
的一些模块。默认情况下,您将获得所有子规格。
如果您需要使用自己的照片编辑器,只需指定除PhotoEditor
之外的子规格
pod 'DKImagePickerController', :subspecs => ['PhotoGallery', 'Camera', 'InlineCamera']
更多信息,请参阅扩展。
Carthage
github "zhangao0086/DKImagePickerController"
如果您使用Carthage构建依赖项,请确保您已将CropViewController.framework
、DKCamera.framework
、DKImagePickerController.framework
、DKPhotoGallery.framework
和SDWebImage.framework
添加到目标中的"Linked Frameworks and Libraries"部分,并在Carthage框架复制构建阶段中包含它们。
入门指南
初始化和展示
let pickerController = DKImagePickerController()
pickerController.didSelectAssets = { (assets: [DKAsset]) in
print("didSelectAssets")
print(assets)
}
self.presentViewController(pickerController, animated: true) {}
````
#### Configurations
```swift
/// Use UIDelegate to Customize the picker UI.
@objc public var UIDelegate: DKImagePickerControllerBaseUIDelegate!
/// Forces deselect of previous selected image. allowSwipeToSelect will be ignored.
@objc public var singleSelect = false
/// Auto close picker on single select
@objc public var autoCloseOnSingleSelect = true
/// The maximum count of assets which the user will be able to select, a value of 0 means no limit.
@objc public var maxSelectableCount = 0
/// Photos will be tagged with the location where they are taken.
/// If true, your Info.plist should include the "Privacy - Location XXX" tag.
open var containsGPSInMetadata = false
/// Set the defaultAssetGroup to specify which album is the default asset group.
public var defaultAssetGroup: PHAssetCollectionSubtype?
/// Allow swipe to select images.
@objc public var allowSwipeToSelect: Bool = false
/// Allow select all
@objc public var allowSelectAll: Bool = false
/// A Bool value indicating whether the inline mode is enabled.
@objc public var inline: Bool = false
/// The type of picker interface to be displayed by the controller.
@objc public var assetType: DKImagePickerControllerAssetType = .allAssets
/// If sourceType is Camera will cause the assetType & maxSelectableCount & allowMultipleTypes & defaultSelectedAssets to be ignored.
@objc public var sourceType: DKImagePickerControllerSourceType = .both
/// A Bool value indicating whether allows to select photos and videos at the same time.
@objc public var allowMultipleTypes = true
/// A Bool value indicating whether to allow the picker auto-rotate the screen.
@objc public var allowsLandscape = false
/// Set the showsEmptyAlbums to specify whether or not the empty albums is shown in the picker.
@objc public var showsEmptyAlbums = true
/// A Bool value indicating whether to allow the picker shows the cancel button.
@objc public var showsCancelButton = false
/// The block is executed when the user presses the cancel button.
@objc public var didCancel: (() -> Void)?
/// The block is executed when the user presses the select button.
@objc public var didSelectAssets: ((_ assets: [DKAsset]) -> Void)?
/// The block is executed when the number of selected assets is changed.
@objc public var selectedChanged: (() -> Void)?
/// A Bool value indicating whether to allow the picker to auto-export the selected assets to the specified directory when done is called.
/// picker will creating a default exporter if exportsWhenCompleted is true and the exporter is nil.
@objc public var exportsWhenCompleted = false
@objc public var exporter: DKImageAssetExporter?
/// Indicates the status of the exporter.
@objc public private(set) var exportStatus = DKImagePickerControllerExportStatus.none {
willSet {
if self.exportStatus != newValue {
self.willChangeValue(forKey: #keyPath(DKImagePickerController.exportStatus))
}
}
didSet {
if self.exportStatus != oldValue {
self.didChangeValue(forKey: #keyPath(DKImagePickerController.exportStatus))
self.exportStatusChanged?(self.exportStatus)
}
}
}
/// The block is executed when the exportStatus is changed.
@objc public var exportStatusChanged: ((DKImagePickerControllerExportStatus) -> Void)?
/// The object that acts as the data source of the picker.
@objc public private(set) lazy var groupDataManager: DKImageGroupDataManager
内嵌模式
let groupDataManagerConfiguration = DKImageGroupDataManagerConfiguration()
groupDataManagerConfiguration.fetchLimit = 10
groupDataManagerConfiguration.assetGroupTypes = [.smartAlbumUserLibrary]
let groupDataManager = DKImageGroupDataManager(configuration: groupDataManagerConfiguration)
self.pickerController = DKImagePickerController(groupDataManager: groupDataManager)
pickerController.inline = true
pickerController.UIDelegate = CustomInlineLayoutUIDelegate(imagePickerController: pickerController)
pickerController.assetType = .allPhotos
pickerController.sourceType = .photo
let pickerView = self.pickerController.view!
pickerView.frame = CGRect(x: 0, y: 170, width: self.view.bounds.width, height: 200)
self.view.addSubview(pickerView)
可定制的用户界面
例如,参见 CustomUIDelegate。
可定制的布局
例如,参见 CustomLayoutUIDelegate。
符合UIAppearance协议
您可以使用外观代理轻松自定义导航栏的外观。
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName : UIFont(name: "Optima-BoldItalic", size: 21)!,
NSForegroundColorAttributeName : UIColor.redColor()
]
导出到文件
默认情况下,选择器使用一个名为《DKImageAssetExporter》的单例对象将《DKAsset》导出到本地文件。
/*
Configuration options for a DKImageAssetExporter. When an exporter is created,
a copy of the configuration object is made - you cannot modify the configuration
of an exporter after it has been created.
*/
@objc
public class DKImageAssetExporterConfiguration: NSObject, NSCopying {
@objc public var imageExportPreset = DKImageExportPresent.compatible
/// videoExportPreset can be used to specify the transcoding quality for videos (via a AVAssetExportPreset* string).
@objc public var videoExportPreset = AVAssetExportPresetHighestQuality
#if swift(>=4.0)
@objc public var avOutputFileType = AVFileType.mov
#else
@objc public var avOutputFileType = AVFileTypeQuickTimeMovie
#endif
@objc public var exportDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("DKImageAssetExporter")
}
/*
A DKImageAssetExporter object exports DKAsset(PHAsset) from album (or iCloud) to the app's tmp directory (by default).
It automatically deletes the exported directories when it receives a UIApplicationWillTerminate notification.
*/
@objc
open class DKImageAssetExporter: DKBaseManager {
/// This method starts an asynchronous export operation of a batch of asset.
@discardableResult
@objc public func exportAssetsAsynchronously(assets: [DKAsset], completion: ((_ info: [AnyHashable : Any]) -> Void)?) -> DKImageAssetExportRequestID
}
此导出器可以自动将HEIF转换为JPEG。
@objc
public enum DKImageExportPresent: Int {
case
compatible, // A preset for converting HEIF formatted images to JPEG.
current // A preset for passing image data as-is to the client.
}
您还可以观察每个资产的导出进度。
@objc
public protocol DKImageAssetExporterObserver {
@objc optional func exporterWillBeginExporting(exporter: DKImageAssetExporter, asset: DKAsset)
/// The progress can be obtained from the DKAsset.
@objc optional func exporterDidUpdateProgress(exporter: DKImageAssetExporter, asset: DKAsset)
/// When the asset's error is not nil, it indicates that an error occurred while exporting.
@objc optional func exporterDidEndExporting(exporter: DKImageAssetExporter, asset: DKAsset)
}
extension DKAsset {
/// The exported file will be placed in this location.
/// All exported files can be automatically cleaned by the DKImageAssetDiskPurger when appropriate.
@objc public var localTemporaryPath: URL?
@objc public var fileName: String?
/// Indicates the file's size in bytes.
@objc public var fileSize: UInt
/// If you export an asset whose data is not on the local device, and you have enabled downloading with the isNetworkAccessAllowed property, the progress indicates the progress of the download. A value of 0.0 indicates that the download has just started, and a value of 1.0 indicates the download is complete.
@objc public var progress: Double
/// Describes the error that occurred if the export has failed or been cancelled.
@objc public var error: Error?
}
例如,参见《自动导出》和《手动导出》。
扩展
此选择器使用《DKImageExtensionController》管理所有扩展,您可以使用《DKImageBaseExtension》和一个指定的《DKImageExtensionType》将其注册起来,以自定义《相机》,《相册》和《照片编辑器》。
/// Registers an extension for the specified type.
public class func registerExtension(extensionClass: DKImageBaseExtension.Type, for type: DKImageExtensionType)
public class func unregisterExtension(for type: DKImageExtensionType)
当一个扩展被触发时,将使用一个提供当前上下文信息的字典调用`perform`函数。
/// Starts the extension.
func perform(with extraInfo: [AnyHashable: Any])
/// Completes the extension.
func finish()
`extraInfo`将为不同的《DKImageExtensionType》提供不同的信息。
摄像机
let didFinishCapturingImage = extraInfo["didFinishCapturingImage"] as? ((UIImage, [AnyHashable : Any]?) -> Void)
let didCancel = extraInfo["didCancel"] as? (() -> Void)
有关自定义摄像机示例,请参阅CustomCameraExtension。
内嵌摄像机
extraInfo
与Camera
相同。
照片库
let groupId = extraInfo["groupId"] as? String
let presentationIndex = extraInfo["presentationIndex"] as? Int
let presentingFromImageView = extraInfo["presentingFromImageView"] as? UIImageView
照片编辑器
let image = extraInfo["image"] as? UIImage
let didFinishEditing = extraInfo["didFinishEditing"] as? ((UIImage, [AnyHashable : Any]?) -> Void)
let metadata = extraInfo["metadata"] as? [AnyHashable : Any]
如何在Objective-C中使用
CocoaPods
如果您使用-
将以下两行添加到您的
Podfile
pod 'DKImagePickerController' use_frameworks!
-
在您的Objective-C文件中导入库
#import <DKImagePickerController/DKImagePickerController-Swift.h>
如果您要在项目中直接使用它
-
将 DKCamera,
DKImageManager
和DKImagePickerController
拖放到您的项目中 -
在您的Objective-C文件中导入库
#import "YourProductModuleName-Swift.h"
然后您可以使用它们
DKImagePickerController *pickerController = [DKImagePickerController new];
[pickerController setDidSelectAssets:^(NSArray * __nonnull assets) {
NSLog(@"didSelectAssets");
}];
[self presentViewController:pickerController animated:YES completion:nil];
本地化
默认支持的语言
en, es, da, de, fr, hu, ja, ko, nb-NO, pt_BR, ru, tr, ur, vi, ar, it, zh-Hans, zh-Hant
您还可以添加一个钩子,以返回您自己的本地化字符串
DKImagePickerControllerResource.customLocalizationBlock = { title in
if title == "picker.select.title" {
return "Test(%@)"
} else {
return nil
}
}
或图片
DKImagePickerControllerResource.customImageBlock = { imageName in
if imageName == "camera" {
return DKImagePickerControllerResource.photoGalleryCheckedImage()
} else {
return nil
}
}
对本项目的贡献
如果您有功能请求或错误报告,请随意通过发送拉取请求或创建新问题来帮助。
许可证
DKImagePickerController 在 MIT 许可证下发布。有关详细信息,请参阅 LICENSE 文件。