import imgly_cameraimport imgly_editorimport SwiftUI
func useCustomEditor() { IMGLYEditorPlugin.builderClosure = { _, metadata in // Make decisions based on your own metadata. if metadata?["use_custom_editor"] as? Bool == true { // Return your custom editor. EditorBuilder.custom { settings, _, _, result in CustomEditor(settings: settings, result: result) } } else { // Return a custom or prebuilt editor. EditorBuilder.design() } }}
private struct CustomEditor: View { init(settings _: EditorSettings, result _: @escaping EditorBuilder.EditorBuilderResult) {}
var body: some View { Text("Custom Editor") }}
func configureCamera() { IMGLYCameraPlugin.builderClosure = { metadata in // Make decisions based on your own metadata. if metadata?["use_custom_camera"] as? Bool == true { // Return your custom camera. CameraBuilder.custom { settings, url, metadata, result in CustomCamera(settings: settings, url: url, metadata: metadata, result: result) } } else { // Return a custom or prebuilt camera. CameraBuilder.default() } }}
private struct CustomCamera: View { init( settings _: CameraSettings, url _: URL?, metadata _: [String: Any]?, result _: @escaping CameraBuilder.CameraBuilderResult, ) {}
var body: some View { Text("Custom Camera") }}package ly.img.editor.flutter.showcases.guides
import androidx.compose.runtime.Composableimport ly.img.camera.core.CameraLayoutModeimport ly.img.camera.core.CameraModeimport ly.img.camera.core.CameraResultimport ly.img.camera.core.CaptureMediaimport ly.img.camera.core.videosimport ly.img.camera.flutter.plugin.IMGLYCameraPluginimport ly.img.editor.flutter.plugin.IMGLYEditorPluginimport ly.img.editor.flutter.plugin.builder.EditorBuilderimport ly.img.editor.flutter.plugin.builder.EditorBuilderResultimport ly.img.editor.flutter.plugin.model.EditorSettings
private fun useCustomEditor() { IMGLYEditorPlugin.builderClosure = { _, metadata -> if (metadata?.get("custom") == true) { EditorBuilder.custom { settings, _, _, result, onClose -> @Composable { CustomEditor(settings, result, onClose) } } } else { EditorBuilder.design() } }}
private fun customizeCamera() { // Configure the [CaptureMedia.Input]. IMGLYCameraPlugin.configurationClosure = { /* * This closure requires returning a [CaptureMedia.Input]. * * You can access the following parameters: * - "cameraSettings": The CameraSettings passed from the Flutter side. * - "engineConfiguration": The EngineConfiguration that includes your license. * - "metadata": Metadata passed from the Flutter side. * - "videoUri": The video reaction URL passed from Flutter, or null. */
if (metadata["is_reactions"] == true) { CaptureMedia.Input( engineConfiguration = engineConfiguration, cameraMode = CameraMode.Reaction( videoUri ?: throw RuntimeException("Missing video URL."), cameraLayoutMode = CameraLayoutMode.Horizontal, positionsSwapped = false, ), ) } else { // Simply return null to use the default camera configuration. null } }
// Adding custom metadata to the CameraResult. IMGLYCameraPlugin.resultClosure = { /* * This closure allows you to add custom metadata of type [Map<String, Any?>] to the CameraResult. * You can access the following values: * - "cameraResult": The native CameraResult returned by the camera. * - "inputMetadata": Metadata passed from the Flutter side when the camera was opened. * * The return value must be a [Map<String, Any?>], which will be passed to the Dart-side * representation of the CameraResult. * * Notes: * - Use `mapOf<String, Any?>()` to return key-value pairs. * - Return `null` if no metadata should be added. */
// Example: Read the result data... val recordings = when (val result = cameraResult) { is CameraResult.Captures -> result.captures.videos is CameraResult.Reaction -> result.reaction else -> emptyList() }
// Return a custom metadata map mapOf( "MY_CUSTOM_KEY" to "MY_CUSTOM_VALUE", ) }}
@Composableprivate fun CustomEditor( settings: EditorSettings, result: EditorBuilderResult, onClose: (Throwable?) -> Unit,) {}import Flutterimport imgly_editorimport IMGLYEditorimport IMGLYEngineimport IMGLYPluginBackgroundRemovalimport IMGLYPluginVoiceIsolationimport SwiftUIimport UIKit
@main@objc class AppDelegate: FlutterAppDelegate { /// A typealias for `EditorBuilder.EditorBuilderResult` for convenient usage. typealias EditorBuilderResult = EditorBuilder.EditorBuilderResult
override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?, ) -> Bool { // swiftlint:disable:next force_cast let controller: FlutterViewController = window?.rootViewController as! FlutterViewController let channel = FlutterMethodChannel(name: "native_cleanup", binaryMessenger: controller.binaryMessenger)
channel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in if call.method == "cleanUp" { if let windowScene = UIApplication.shared.connectedScenes .filter({ $0.activationState == .foregroundActive }) .first as? UIWindowScene { if let rootViewController = windowScene.windows .filter(\.isKeyWindow).first?.rootViewController { rootViewController.dismiss(animated: true, completion: { result(true) }) } else { result(nil) } } else { result(nil) } } else { result(FlutterMethodNotImplemented) } }
GeneratedPluginRegistrant.register(with: self)
// Apply the custom editor. assignCustomEditor()
return super.application(application, didFinishLaunchingWithOptions: launchOptions) }
/// Assings the custom editors. private func assignCustomEditor() { /// Returns a custom or default editor based on the metadata. /// - Parameters: /// - defaultEditor: The default editor. /// - customEditor: The custom editor. /// - metadata: The metadata used to determine which editor to use. /// - Returns: The corresponding `EditorBuilder.Builder`. func defaultOrCustomEditor( defaultEditor: @escaping EditorBuilder.Builder, customEditor: @escaping EditorBuilder.Builder, metadata: [String: Any]?, ) -> EditorBuilder.Builder { if let enabled = metadata?["custom"] as? Bool, enabled == true { customEditor } else { defaultEditor } }
/// Returns the editor of the plugin that the metadata names. /// - Parameter metadata: The metadata used to determine the plugin. /// - Returns: The corresponding `EditorBuilder.Builder`, or `nil` when the metadata names no plugin. func pluginEditor(metadata: [String: Any]?) -> EditorBuilder.Builder? { switch metadata?["plugin"] as? String { case "backgroundRemoval": EditorBuilder.custom { settings, _, _, result in BackgroundRemovalEditor(settings: settings, result: result) } case "voiceIsolation": EditorBuilder.custom { settings, _, _, result in VoiceIsolationEditor(settings: settings, result: result) } default: nil } }
IMGLYEditorPlugin.builderClosure = { preset, metadata in if let pluginEditor = pluginEditor(metadata: metadata) { return pluginEditor } return switch preset { case .postcard: defaultOrCustomEditor( defaultEditor: EditorBuilder.postcard(), customEditor: EditorBuilder.custom { settings, _, _, result in CustomPostcardEditor(settings: settings, result: result) }, metadata: metadata, ) case .photo: defaultOrCustomEditor( defaultEditor: EditorBuilder.photo(), customEditor: EditorBuilder.custom { settings, _, _, result in CustomPhotoEditor(settings: settings, result: result) }, metadata: metadata, ) case .video: defaultOrCustomEditor( defaultEditor: EditorBuilder.video(), customEditor: EditorBuilder.custom { settings, _, _, result in CustomVideoEditor(settings: settings, result: result) }, metadata: metadata, ) case .design: defaultOrCustomEditor( defaultEditor: EditorBuilder.design(), customEditor: EditorBuilder.custom { settings, _, _, result in CustomDesignEditor(settings: settings, result: result) }, metadata: metadata, ) case .apparel: defaultOrCustomEditor( // NOTE: This custom editor is only used for UITests. // By default, simply use `EditorBuilder.apparel()` instead. defaultEditor: EditorBuilder.custom { settings, _, _, result in ApparelEditorForUITests(settings: settings, result: result) }, customEditor: EditorBuilder.custom { settings, _, _, result in CustomApparelEditor(settings: settings, result: result) }, metadata: metadata, ) case nil: EditorBuilder.custom { settings, _, _, result in CustomDesignEditor(settings: settings, result: result) } } } }}
// MARK: - Custom Editors
/// An extension containig the custom editor implementations.extension AppDelegate { /// Derives `EngineSettings` for a given `EditorSettings`. /// - Parameters: /// - settings: The `EditorSettings` to derive the settings from. /// - Returns: The derived `EngineSettings`. private static func engineSettings(for settings: EditorSettings) -> EngineSettings { EngineSettings(license: settings.license, userID: settings.userId, baseURL: URL(string: settings.baseUri)) }
/// A custom design editor. private struct CustomDesignEditor: View { private let settings: EditorSettings private let result: EditorBuilderResult
init(settings: EditorSettings, result: @escaping EditorBuilderResult) { self.settings = settings self.result = result }
var body: some View { NavigationView { Editor(engineSettings(for: settings)) .imgly.configuration { DesignEditorConfiguration { builder in builder.onCreate { engine, _ in if let createScene = try OnCreate.loadFromSettings(settings) { try await DesignEditorConfiguration.defaultOnCreate(createScene: createScene)(engine) } else { try await DesignEditorConfiguration.defaultOnCreate()(engine) } try engine.asset.addSource(UnsplashAssetSource(host: Secrets.unsplashHost)) } builder.onExport { engine, _, _ in do { let editorResult = try await OnExport.export(engine, .png) result(.success(editorResult)) } catch { result(.failure(error)) } } } ModalEditorConfiguration(result: result) } }.navigationViewStyle(.stack) } }
/// A custom apparel editor. private struct CustomApparelEditor: View { private let settings: EditorSettings private let result: EditorBuilderResult
init(settings: EditorSettings, result: @escaping EditorBuilderResult) { self.settings = settings self.result = result }
var body: some View { NavigationView { Editor(engineSettings(for: settings)) .imgly.configuration { ApparelEditorConfiguration { builder in builder.onCreate { engine, _ in if let createScene = try OnCreate.loadFromSettings(settings) { try await ApparelEditorConfiguration.defaultOnCreate(createScene: createScene)(engine) } else { try await ApparelEditorConfiguration.defaultOnCreate()(engine) } try engine.asset.addSource(UnsplashAssetSource(host: Secrets.unsplashHost))
// This is only needed for UITests. try engine.editor.setSettingBool("showBuildVersion", value: false) } builder.onExport { engine, _, _ in do { let editorResult = try await OnExport.export(engine, .pdf) result(.success(editorResult)) } catch { result(.failure(error)) } } } ModalEditorConfiguration(result: result) } }.navigationViewStyle(.stack) } }
/// A custom photo editor. private struct CustomPhotoEditor: View { private let settings: EditorSettings private let result: EditorBuilderResult
init(settings: EditorSettings, result: @escaping EditorBuilderResult) { self.settings = settings self.result = result }
var body: some View { NavigationView { Editor(engineSettings(for: settings)) .imgly.configuration { PhotoEditorConfiguration { builder in builder.onCreate { engine, _ in if let createScene = try OnCreate.loadFromSettings(settings) { try await PhotoEditorConfiguration.defaultOnCreate(createScene: createScene)(engine) } else { try await PhotoEditorConfiguration.defaultOnCreate()(engine) } try engine.asset.addSource(UnsplashAssetSource(host: Secrets.unsplashHost)) } builder.onExport { engine, _, _ in do { let editorResult = try await OnExport.export(engine, .png) result(.success(editorResult)) } catch { result(.failure(error)) } } } ModalEditorConfiguration(result: result) } }.navigationViewStyle(.stack) } }
/// A custom video editor. private struct CustomVideoEditor: View { private let settings: EditorSettings private let result: EditorBuilderResult
init(settings: EditorSettings, result: @escaping EditorBuilderResult) { self.settings = settings self.result = result }
var body: some View { NavigationView { Editor(engineSettings(for: settings)) .imgly.configuration { VideoEditorConfiguration { builder in builder.onCreate { engine, _ in if let createScene = try OnCreate.loadFromSettings(settings) { try await VideoEditorConfiguration.defaultOnCreate(createScene: createScene)(engine) } else { try await VideoEditorConfiguration.defaultOnCreate()(engine) } try engine.asset.addSource(UnsplashAssetSource(host: Secrets.unsplashHost)) } builder.onExport { engine, eventHandler, _ in do { let editorResult = try await OnExport.exportVideo(engine, eventHandler, .mp4) result(.success(editorResult)) } catch { if error is CancellationError { return } result(.failure(error)) } } } ModalEditorConfiguration(result: result) } }.navigationViewStyle(.stack) } }
/// A custom postcard editor. private struct CustomPostcardEditor: View { private let settings: EditorSettings private let result: EditorBuilderResult
init(settings: EditorSettings, result: @escaping EditorBuilderResult) { self.settings = settings self.result = result }
var body: some View { NavigationView { Editor(engineSettings(for: settings)) .imgly.configuration { PostcardEditorConfiguration { builder in builder.onCreate { engine, _ in if let createScene = try OnCreate.loadFromSettings(settings) { try await PostcardEditorConfiguration.defaultOnCreate(createScene: createScene)(engine) } else { try await PostcardEditorConfiguration.defaultOnCreate()(engine) } try engine.asset.addSource(UnsplashAssetSource(host: Secrets.unsplashHost)) } builder.onExport { engine, _, _ in do { let editorResult = try await OnExport.export(engine, .pdf) result(.success(editorResult)) } catch { result(.failure(error)) } } } ModalEditorConfiguration(result: result) } }.navigationViewStyle(.stack) } }
/// A photo editor with the background removal plugin. private struct BackgroundRemovalEditor: View { private let settings: EditorSettings private let result: EditorBuilderResult
init(settings: EditorSettings, result: @escaping EditorBuilderResult) { self.settings = settings self.result = result }
var body: some View { NavigationView { Editor(engineSettings(for: settings)) .imgly.configuration { PhotoEditorConfiguration { builder in builder.onCreate { engine, _ in if let createScene = try OnCreate.loadFromSettings(settings) { try await PhotoEditorConfiguration.defaultOnCreate(createScene: createScene)(engine) } else { try await PhotoEditorConfiguration.defaultOnCreate()(engine) } } builder.onExport { engine, _, _ in do { let editorResult = try await OnExport.export(engine, .png) result(.success(editorResult)) } catch { result(.failure(error)) } } } ModalEditorConfiguration(result: result) BackgroundRemovalPlugin() } }.navigationViewStyle(.stack) } }
/// A video editor with the voice isolation plugin. private struct VoiceIsolationEditor: View { private let settings: EditorSettings private let result: EditorBuilderResult
init(settings: EditorSettings, result: @escaping EditorBuilderResult) { self.settings = settings self.result = result }
var body: some View { NavigationView { Editor(engineSettings(for: settings)) .imgly.configuration { VideoEditorConfiguration { builder in builder.onCreate { engine, _ in if let createScene = try OnCreate.loadFromSettings(settings) { try await VideoEditorConfiguration.defaultOnCreate(createScene: createScene)(engine) } else { try await VideoEditorConfiguration.defaultOnCreate()(engine) } } // The "Isolate Voice" button is in the inspector bar, so select the clip. builder.onLoaded { context, existing in try await existing() let engine = context.engine if let clip = try engine.block.find(byType: .graphic) .first(where: { VoiceIsolationPlugin.canIsolateVoice(of: $0, engine: engine) }) { try engine.block.setSelected(clip, selected: true) } } builder.onExport { engine, eventHandler, _ in do { let editorResult = try await OnExport.exportVideo(engine, eventHandler, .mp4) result(.success(editorResult)) } catch { if error is CancellationError { return } result(.failure(error)) } } } ModalEditorConfiguration(result: result) VoiceIsolationPlugin() } }.navigationViewStyle(.stack) } }
/// A custom apparel editor for UITests. private struct ApparelEditorForUITests: View { private let settings: EditorSettings private let result: EditorBuilderResult
init(settings: EditorSettings, result: @escaping EditorBuilderResult) { self.settings = settings self.result = result }
var body: some View { NavigationView { Editor(engineSettings(for: settings)) .imgly.configuration { ApparelEditorConfiguration { builder in builder.onCreate { engine, _ in if let createScene = try OnCreate.loadFromSettings(settings) { try await ApparelEditorConfiguration.defaultOnCreate(createScene: createScene)(engine) } else { try await ApparelEditorConfiguration.defaultOnCreate()(engine) }
// This is only needed for UITests. try engine.editor.setSettingBool("showBuildVersion", value: false) } builder.onExport { engine, _, _ in do { let editorResult = try await OnExport.export(engine, .pdf) result(.success(editorResult)) } catch { result(.failure(error)) } } } ModalEditorConfiguration(result: result) } }.navigationViewStyle(.stack) } }}package ly.img.editor.flutter.showcases
import androidx.compose.runtime.Composableimport androidx.compose.runtime.rememberimport androidx.core.net.toUriimport io.flutter.embedding.android.FlutterActivityimport io.flutter.embedding.engine.FlutterEngineimport kotlinx.coroutines.CancellationExceptionimport ly.img.editor.Editorimport ly.img.editor.configuration.apparel.ApparelConfigurationBuilderimport ly.img.editor.configuration.apparel.callback.onCreateimport ly.img.editor.configuration.apparel.callback.onExportimport ly.img.editor.configuration.apparel.callback.onLoadAssetSourcesimport ly.img.editor.configuration.design.DesignConfigurationBuilderimport ly.img.editor.configuration.design.callback.onCreateimport ly.img.editor.configuration.design.callback.onExportimport ly.img.editor.configuration.design.callback.onLoadAssetSourcesimport ly.img.editor.configuration.photo.PhotoConfigurationBuilderimport ly.img.editor.configuration.photo.callback.onCreateimport ly.img.editor.configuration.photo.callback.onExportimport ly.img.editor.configuration.photo.callback.onLoadAssetSourcesimport ly.img.editor.configuration.postcard.PostcardConfigurationBuilderimport ly.img.editor.configuration.postcard.callback.onCreateimport ly.img.editor.configuration.postcard.callback.onExportimport ly.img.editor.configuration.postcard.callback.onLoadAssetSourcesimport ly.img.editor.configuration.video.VideoConfigurationBuilderimport ly.img.editor.configuration.video.callback.onCreateimport ly.img.editor.configuration.video.callback.onExportimport ly.img.editor.configuration.video.callback.onLoadAssetSourcesimport ly.img.editor.configuration.video.callback.onLoadedimport ly.img.editor.core.configuration.EditorConfigurationimport ly.img.editor.core.configuration.rememberimport ly.img.editor.core.configuration.thenimport ly.img.editor.core.library.AssetLibraryimport ly.img.editor.core.library.AssetTypeimport ly.img.editor.core.library.LibraryCategoryimport ly.img.editor.core.library.LibraryContentimport ly.img.editor.core.library.addSectionimport ly.img.editor.core.library.data.AssetSourceTypeimport ly.img.editor.flutter.plugin.IMGLYEditorPluginimport ly.img.editor.flutter.plugin.builder.Builderimport ly.img.editor.flutter.plugin.builder.EditorBuilderimport ly.img.editor.flutter.plugin.builder.EditorBuilderDefaultsimport ly.img.editor.flutter.plugin.builder.EditorBuilderResultimport ly.img.editor.flutter.plugin.model.EditorPresetimport ly.img.editor.flutter.plugin.model.EditorSettingsimport ly.img.editor.flutter.plugin.model.EditorSourceTypeimport ly.img.editor.plugin.backgroundRemoval.IMGLYBackgroundRemovalPluginimport ly.img.editor.plugin.voiceIsolation.IMGLYVoiceIsolationPluginimport ly.img.editor.plugin.voiceIsolation.canIsolateVoiceimport ly.img.engine.DesignBlockTypeimport ly.img.engine.MimeType
class MainActivity : FlutterActivity() { private val unsplashAssetSource = UnsplashAssetSource(Secrets.unsplashHost) private val unsplashSection = LibraryContent.Section( titleRes = R.string.unsplash, sourceTypes = listOf(AssetSourceType(sourceId = unsplashAssetSource.sourceId)), assetType = AssetType.Image, )
override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) // Snapshot-test bridge: real in the debug variant, a no-op in release. SnapshotChannel.register(flutterEngine, this) }
override fun onStart() { super.onStart()
IMGLYEditorPlugin.builderClosure = { preset, metadata -> pluginBuilder(metadata) ?: when (preset) { EditorPreset.APPAREL -> { val customBuilder = EditorBuilder.custom { settings, _, _, result, onClose -> @Composable { CustomApparelEditor(settings, result, onClose) } } builderOrCustom(EditorBuilder.apparel(), customBuilder, metadata) }
EditorPreset.POSTCARD -> { val customBuilder = EditorBuilder.custom { settings, _, _, result, onClose -> @Composable { CustomPostcardEditor(settings, result, onClose) } } builderOrCustom(EditorBuilder.postcard(), customBuilder, metadata) }
EditorPreset.PHOTO -> { val customBuilder = EditorBuilder.custom { settings, _, _, result, onClose -> @Composable { CustomPhotoEditor(settings, result, onClose) } } builderOrCustom(EditorBuilder.photo(), customBuilder, metadata) }
EditorPreset.DESIGN -> { val customBuilder = EditorBuilder.custom { settings, _, _, result, onClose -> @Composable { CustomDesignEditor(settings, result, onClose) } } builderOrCustom(EditorBuilder.design(), customBuilder, metadata) }
EditorPreset.VIDEO -> { val customBuilder = EditorBuilder.custom { settings, _, _, result, onClose -> @Composable { CustomVideoEditor(settings, result, onClose) } } builderOrCustom(EditorBuilder.video(), customBuilder, metadata) }
null -> { val customBuilder = EditorBuilder.custom { settings, _, _, result, onClose -> @Composable { CustomDesignEditor(settings, result, onClose) } } builderOrCustom(EditorBuilder.design(), customBuilder, metadata) } } } }
override fun onDestroy() { super.onDestroy()
IMGLYEditorPlugin.builderClosure = null }
@Composable fun CustomApparelEditor( settings: EditorSettings, result: EditorBuilderResult, onClose: (Throwable?) -> Unit, ) { Editor( license = settings.license, baseUri = settings.baseUri.toUri(), userId = settings.userId, configuration = { EditorConfiguration.remember(::ApparelConfigurationBuilder) { onCreate = { onCreate( createScene = { EditorBuilderDefaults.onCreateScene( scope = this@Editor, settings = settings, defaultUri = "file:///android_asset/scene/apparel.scene".toUri(), ) }, loadAssetSources = { onLoadAssetSources() editorContext.engine.asset.addSource(unsplashAssetSource) }, ) } onExport = { onExport( postExport = { val result = EditorBuilderDefaults.getExportResult( scope = this@Editor, byteBuffer = it, mimeType = MimeType.PDF, ) result(Result.success(result)) }, error = { result(Result.failure(it)) }, ) } assetLibrary = { remember { AssetLibrary.getDefault( images = LibraryCategory.Images.addSection(unsplashSection), ) } } } }, ) { onClose(it) } }
@Composable fun CustomDesignEditor( settings: EditorSettings, result: EditorBuilderResult, onClose: (Throwable?) -> Unit, ) { Editor( license = settings.license, baseUri = settings.baseUri.toUri(), userId = settings.userId, configuration = { EditorConfiguration.remember(::DesignConfigurationBuilder) { onCreate = { onCreate( createScene = { EditorBuilderDefaults.onCreateScene( scope = this@Editor, settings = settings, defaultUri = "file:///android_asset/scene/design.scene".toUri(), ) }, loadAssetSources = { onLoadAssetSources() editorContext.engine.asset.addSource(unsplashAssetSource) }, ) } onExport = { onExport( postExport = { val result = EditorBuilderDefaults.getExportResult( scope = this@Editor, byteBuffer = it, mimeType = MimeType.PDF, ) result(Result.success(result)) }, error = { result(Result.failure(it)) }, ) } assetLibrary = { remember { AssetLibrary.getDefault( images = LibraryCategory.Images.addSection(unsplashSection), ) } } } }, ) { onClose(it) } }
@Composable fun CustomPhotoEditor( settings: EditorSettings, result: EditorBuilderResult, onClose: (Throwable?) -> Unit, ) { Editor( license = settings.license, baseUri = settings.baseUri.toUri(), userId = settings.userId, configuration = { EditorConfiguration.remember(::PhotoConfigurationBuilder) { onCreate = { onCreate( createScene = { EditorBuilderDefaults.onCreateScene( scope = this@Editor, settings = settings, defaultUri = EditorBuilderDefaults.defaultPhotoUri, sourceType = EditorSourceType.IMAGE, ) }, loadAssetSources = { onLoadAssetSources() editorContext.engine.asset.addSource(unsplashAssetSource) }, ) } onExport = { onExport( postExport = { val result = EditorBuilderDefaults.getExportResult( scope = this@Editor, byteBuffer = it, mimeType = MimeType.PNG, ) result(Result.success(result)) }, error = { result(Result.failure(it)) }, ) } assetLibrary = { remember { AssetLibrary.getDefault( images = LibraryCategory.Images.addSection(unsplashSection), ) } } } }, ) { onClose(it) } }
@Composable fun CustomPostcardEditor( settings: EditorSettings, result: EditorBuilderResult, onClose: (Throwable?) -> Unit, ) { Editor( license = settings.license, baseUri = settings.baseUri.toUri(), userId = settings.userId, configuration = { EditorConfiguration.remember(::PostcardConfigurationBuilder) { onCreate = { onCreate( createScene = { EditorBuilderDefaults.onCreateScene( scope = this@Editor, settings = settings, defaultUri = "file:///android_asset/scene/postcard.scene".toUri(), ) }, loadAssetSources = { onLoadAssetSources() editorContext.engine.asset.addSource(unsplashAssetSource) }, ) } onExport = { onExport( postExport = { val result = EditorBuilderDefaults.getExportResult( scope = this@Editor, byteBuffer = it, mimeType = MimeType.PDF, ) result(Result.success(result)) }, error = { result(Result.failure(it)) }, ) } assetLibrary = { remember { AssetLibrary.getDefault( images = LibraryCategory.Images.addSection(unsplashSection), ) } } } }, ) { onClose(it) } }
@Composable fun CustomVideoEditor( settings: EditorSettings, result: EditorBuilderResult, onClose: (Throwable?) -> Unit, ) { Editor( license = settings.license, baseUri = settings.baseUri.toUri(), userId = settings.userId, configuration = { EditorConfiguration.remember(::VideoConfigurationBuilder) { onCreate = { onCreate( createScene = { EditorBuilderDefaults.onCreateScene( scope = this@Editor, settings = settings, defaultUri = "file:///android_asset/scene/video.scene".toUri(), ) }, loadAssetSources = { onLoadAssetSources() editorContext.engine.asset.addSource(unsplashAssetSource) }, ) } onExport = { onExport( postExport = { val result = EditorBuilderDefaults.getExportResult( scope = this@Editor, byteBuffer = it, mimeType = MimeType.MP4, ) exportStatus = null result(Result.success(result)) }, error = { exportStatus = null // A cancelled export keeps the editor open. if (it !is CancellationException) { result(Result.failure(it)) } }, ) } assetLibrary = { remember { AssetLibrary.getDefault( includeAVResources = true, images = LibraryCategory.Images.addSection(unsplashSection), ) } } } }, ) { onClose(it) } }
@Composable fun BackgroundRemovalEditor( settings: EditorSettings, result: EditorBuilderResult, onClose: (Throwable?) -> Unit, ) { Editor( license = settings.license, baseUri = settings.baseUri.toUri(), userId = settings.userId, configuration = { EditorConfiguration .remember(::PhotoConfigurationBuilder) { onCreate = { onCreate( createScene = { EditorBuilderDefaults.onCreateScene( scope = this@Editor, settings = settings, defaultUri = EditorBuilderDefaults.defaultPhotoUri, sourceType = EditorSourceType.IMAGE, ) }, ) } onExport = { onExport( postExport = { val result = EditorBuilderDefaults.getExportResult( scope = this@Editor, byteBuffer = it, mimeType = MimeType.PNG, ) result(Result.success(result)) }, error = { result(Result.failure(it)) }, ) } } .then(::IMGLYBackgroundRemovalPlugin) }, ) { onClose(it) } }
@Composable fun VoiceIsolationEditor( settings: EditorSettings, result: EditorBuilderResult, onClose: (Throwable?) -> Unit, ) { Editor( license = settings.license, baseUri = settings.baseUri.toUri(), userId = settings.userId, configuration = { EditorConfiguration .remember(::VideoConfigurationBuilder) { onCreate = { onCreate( createScene = { EditorBuilderDefaults.onCreateScene( scope = this@Editor, settings = settings, defaultUri = "file:///android_asset/scene/video.scene".toUri(), ) }, ) } // The "Isolate Voice" button is in the inspector bar, so select the clip. Select it before the // default onLoaded, which observes the editor until it closes and does not return. onLoaded = { val engine = editorContext.engine engine.block .findByType(DesignBlockType.Graphic) .firstOrNull { canIsolateVoice(it, engine) } ?.let { engine.block.setSelected(it, selected = true) } onLoaded() } onExport = { onExport( postExport = { val result = EditorBuilderDefaults.getExportResult( scope = this@Editor, byteBuffer = it, mimeType = MimeType.MP4, ) exportStatus = null result(Result.success(result)) }, error = { exportStatus = null // A cancelled export keeps the editor open. if (it !is CancellationException) { result(Result.failure(it)) } }, ) } } .then(::IMGLYVoiceIsolationPlugin) }, ) { onClose(it) } }
/** Returns the builder of the editor with the plugin that [metadata] names, or null when it names none. */ private fun pluginBuilder(metadata: Map<String, Any>?): Builder? = when (metadata?.get("plugin")) { "backgroundRemoval" -> EditorBuilder.custom { settings, _, _, result, onClose -> @Composable { BackgroundRemovalEditor(settings, result, onClose) } }
"voiceIsolation" -> EditorBuilder.custom { settings, _, _, result, onClose -> @Composable { VoiceIsolationEditor(settings, result, onClose) } }
else -> null }
private fun builderOrCustom( defaultBuilder: Builder, customBuilder: Builder, metadata: Map<String, Any>?, ): Builder { if (metadata?.get("custom") == true) { return customBuilder } return defaultBuilder }}The Flutter imgly_editor plugin is built on top of the native Android and iOS UI implementation and has no dedicated Flutter UI.
However, you still have access to the same customization options as for iOS and Android.
To use them you need to configure them natively for both platforms.
Native Interfaces#
In order to allow intuitive and easily accessible native customization of the editors, we provide dedicated interfaces and convenience functions for both iOS and Android.
The editor that is opened via the IMGLYEditor.openEditor() function can be completely customized and exchanged.
For this to work you can use the IMGLYEditorPlugin.builderClosure which provides an optional EditorPreset and metadata
with which you can provide any prebuilt or custom editor view. The metadata parameter of the openEditor function can be utilized
to provide customization details from the Flutter side of your app to the native side:
iOS#
On iOS, we provide fallback functions for our default editors via:
EditorBuilder.design()EditorBuilder.apparel()EditorBuilder.photo()EditorBuilder.video()EditorBuilder.postcard()
In case you want a completely custom UI, you can use the EditorBuilder.custom function that allows you to return a custom View based on a given EditorConfig, an EditorPreset, metadata and an EditorBuilderResult:
1. Import the dependencies:#
import imgly_cameraimport imgly_editorimport SwiftUILeave out import imgly_camera if your app does not use the imgly_camera plugin.
2. Assign your custom editor:#
IMGLYEditorPlugin.builderClosure = { _, metadata in // Make decisions based on your own metadata. if metadata?["use_custom_editor"] as? Bool == true { // Return your custom editor. EditorBuilder.custom { settings, _, _, result in CustomEditor(settings: settings, result: result) } } else { // Return a custom or prebuilt editor. EditorBuilder.design() }}Further, we provide convenience extensions both for the OnCreate and OnExport callbacks to reduce the amount of code you need to write. For a detailed example, please take a look at our showcases app.
Android#
On Android, we provide fallback functions for our default editors via
EditorBuilder.design()EditorBuilder.apparel()EditorBuilder.photo()EditorBuilder.postcard().
In case you want a completely custom UI, you can use the EditorBuilder.custom function that allows you to return a custom @Composable function based on a given EditorConfig, an EditorPreset, metadata and an EditorBuilderResult:
1. Turn on Jetpack Compose in your app module:#
The custom editor is a @Composable function, so your app module needs Jetpack Compose. The imgly_editor plugin brings the editor and Compose libraries, so you add no Gradle dependency.
First, declare the Compose Compiler Gradle plugin in android/settings.gradle.kts, as described in Declare the Compose Compiler Plugin. Then apply it in android/app/build.gradle.kts and turn on Compose. Add only the lines marked +, and keep the other lines of your file:
plugins { id("com.android.application") id("org.jetbrains.kotlin.plugin.compose") // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. id("dev.flutter.flutter-gradle-plugin")}
android { (...) buildFeatures { compose = true }}The version of the Compose Compiler plugin must match the Kotlin version that your build uses. To see it, run ./gradlew :app:dependencies --configuration kotlinCompilerClasspath in android/ and read the kotlin-compiler-embeddable version.
Kotlin 1.9.10, which Flutter before 3.44 still accepts, has no Compose Compiler plugin. Use the composeOptions block inside the android section instead of both plugin lines, and keep compose = true:
android { (...) buildFeatures { compose = true } composeOptions { kotlinCompilerExtensionVersion = "1.5.3" }}If your project uses Groovy build files (settings.gradle, build.gradle), write id "org.jetbrains.kotlin.plugin.compose" and compose true instead.
2. Import the dependencies:#
import androidx.compose.runtime.Composableimport ly.img.camera.core.CameraLayoutModeimport ly.img.camera.core.CameraModeimport ly.img.camera.core.CameraResultimport ly.img.camera.core.CaptureMediaimport ly.img.camera.core.videosimport ly.img.camera.flutter.plugin.IMGLYCameraPluginimport ly.img.editor.flutter.plugin.IMGLYEditorPluginimport ly.img.editor.flutter.plugin.builder.EditorBuilderimport ly.img.editor.flutter.plugin.builder.EditorBuilderResultimport ly.img.editor.flutter.plugin.model.EditorSettingsLeave out the ly.img.camera imports if your app does not use the imgly_camera plugin.
3. Assign your custom editor:#
IMGLYEditorPlugin.builderClosure = { _, metadata -> if (metadata?.get("custom") == true) { EditorBuilder.custom { settings, _, _, result, onClose -> @Composable { CustomEditor(settings, result, onClose) } } } else { EditorBuilder.design() }}Further, we provide a class called EditorDefaults which contains convenience methods for both the OnCreate and OnExport callbacks to reduce the amount of code you need to write. For a detailed example, please take a look here.
Add a Plugin#
A plugin adds a feature to the native editor, such as background removal or voice isolation. The plugins overview for iOS and Android lists the plugins, and each plugin’s guide gives its dependency, its import and its options. In a Flutter app, two things differ:
- The dependency uses exactly the version of
imgly_editor. Add the Swift package to the Runner target inios/Runner.xcworkspace, and the Android artifact toandroid/app/build.gradle. The Android plugin needs the Compose setup from step 1 of the Android section above. - The plugin goes into the editor that your
builderClosurereturns, after the editor configuration.
On iOS, for background removal:
BackgroundRemovalPlugin()On Android:
.then(::IMGLYBackgroundRemovalPlugin)The Plugins section of our showcases app opens background removal and voice isolation: see the editors in AppDelegate.swift and MainActivity.kt.
Troubleshooting: with CocoaPods (Flutter before 3.44, or Swift Package Manager turned off), add the plugin’s pod,
such as IMGLYPluginBackgroundRemoval, to the Runner target instead of the Swift package. The
showcases README
shows the Podfile.