flutter_image_cropper

repository·master·Indexed 21 days ago

https://github.com/hnvn/flutter_image_cropper

A Flutter plugin providing image cropping and rotation for Android, iOS, and Web. It leverages native libraries including uCrop for Android, TOCropViewController for iOS, and Cropper.js for Web. The plugin allows for platform-specific UI customization via AndroidUiSettings, IOUiSettings, and WebUiSettings, and supports custom aspect ratio presets through the CropAspectRatioPresetData interface.

Tokens
6.7K
Snippets
16
Records
24
Agent score
76%

What's inside flutter_image_cropper

  1. Configure Web View Modes and Drag Modes

    master

    When using WebUiSettings on the web, you can define specific behaviors for the cropper via viewwMode and dragMode.

    View Modes (WebViewMode)

    • 0: No restrictions (crop box can extend outside the canvas).
    • 1: Restrict the crop box to not exceed the size of the canvas.
    • 2: Restrict the minimum canvas size to fit within the container.
    • 3: Restrict the minimum canvas size to fill the container.

    Drag Modes (WebDragMode)

    • crop: Create a new crop box.
    • move: Move the canvas.
    • none: Do nothing.
  2. How Image Cropper works across platforms

    master

    The image_cropper plugin does not perform image manipulation in Dart. Instead, it uses Flutter Platform Channels to communicate with native libraries to provide a high-performance cropping and rotation experience. Because it relies on native implementations, the user interface (UI) will differ depending on the platform:

  3. Install Image Cropper on Web

    master

    For Web support, you must include the cropperjs CSS and JavaScript files within the <head> tag of your web/index.html file.

    <head>
      ....
    
      <!-- cropperjs -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.css" />
      <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.js"></script>
    
      ....
    </head>
  4. Implement a Custom Web Dialog or Route

    master

    If you use customDialogBuilder or customRouteBuilder in WebUiSettings, you must manually handle the initialization and the cropping trigger to ensure the plugin receives the result.

    1. Initialization: You must call the provided initCropper() function inside your widget's initState.
    2. Cropping: You must call the provided crop() function and return the result to the plugin using Navigator.of(context).pop(result).
    class CropperDialog extends StatefulWidget {
      final dynamic cropper;
      final VoidCallback initCropper;
      final Future<dynamic> Function() crop;
      // ... other params
    
      @override
      _CropperDialogState createState() => _CropperDialogState();
    }
    
    class _CropperDialogState extends State<CropperDialog> {
      @override
      void initState() {
        super.initState();
        // IMPORTANT: must call this function to initialize the Cropper object
        widget.initCropper();
      }
    
      @override
      Widget build(BuildContext context) {
        return Dialog(
          child: Column(
            children: [
              widget.cropper, // The cropper widget
              TextButton(
                onPressed: () async {
                  // IMPORTANT: call crop() and pop the result to the plugin
                  final result = await widget.crop();
                  Navigator.of(context).pop(result);
                },
                child: Text('Crop'),
              ),
            ],
          ),
        );
      }
    }
    
    // Usage in WebUiSettings
    WebUiSettings(
      customDialogBuilder: (cropper, initCropper, crop, rotate, scale) {
        return CropperDialog(
          cropper: cropper,
          initCropper: initCropper,
          crop: crop,
          rotate: rotate,
          scale: scale,
        );
      },
    )
      class CropperDialog extends StatefulWidget {
        ...
      }  
    
      class _CropperDialogState extends State<CropperDialog> {
        @override
        void initState() {
          super.initState();
          /// IMPORTANT: must to call this function
          widget.initCropper();
        }
    
        @override
        Widget build(BuildContext context) {
          Dialog(
            child: Column(
              children: [
                ...
                cropper,
                ...
                TextButton(
                  onPressed: () async {
                    /// IMPORTANT: to call crop() function and return
                    /// result data to plugin, for example:
                    final result = await crop();
                    Navigator.of(context).pop(result);
                  },
                  child: Text('Crop'),
                )
              ]
            ),
          );
        }
      }
    
      WebUiSettings(
        ...
        customDialogBuilder: (cropper, initCropper, crop, rotate, scale) {
          return CropperDialog(
            cropper: cropper,
            initCropper: initCropper,
            crop: crop,
            rotate: rotate,
            scale: scale,
          );
        },
        ...
      )
  5. Install Image Cropper on Android

    master

    To use the plugin on Android, you must register the UCropActivity in your android/app/src/main/AndroidManifest.xml file.

    Note: From version 1.2.0 onwards, your Android project must be migrated to the v2 embedding.

    <activity
      android:name="com.yalantis.ucrop.UCropActivity"
      android:screenOrientation="portrait"
      android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
  6. Customize iOS Launch Screen Assets

    master

    To change the launch screen image for the iOS version of your Flutter application, you can either replace the image files directly in the ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory or use Xcode.

    To use Xcode:

    1. Open your project's iOS workspace using open ios/Runner.xcworkspace.
    2. In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
    3. Drag and drop your desired image assets into the asset catalog.
    open ios/Runner.xcworkspace
  7. Use ImageCropper to crop an image

    master

    To crop an image, call cropImage on an instance of ImageCropper. You must provide a sourcePath (the path to the image file) and a list of uiSettings to configure the cropping interface for each platform (Android, iOS, and Web). The method returns a CroppedFile containing the resulting image.

    import 'package:image_cropper/image_cropper.dart';
    
    CroppedFile croppedFile = await ImageCropper().cropImage(
        sourcePath: imageFile.path,
        uiSettings: [
          AndroidUiSettings(
            toolbarTitle: 'Cropper',
            toolbarColor: Colors.deepOrange,
            toolbarWidgetColor: Colors.white,
            aspectRatioPresets: [
              CropAspectRatioPreset.original,
              CropAspectRatioPreset.square,
              CropAspectRatioPresetCustom(),
            ],
          ),
          IOSUiSettings(
            title: 'Cropper',
            aspectRatioPresets: [
              CropAspectRatioPreset.original,
              CropAspectRatioPreset.square,
              CropAspectRatioPresetCustom(), // IMPORTANT: iOS supports only one custom aspect ratio in preset list
            ],
          ),
          WebUiSettings(
            context: context,
          ),
        ],
      );
    
    class CropAspectRatioPresetCustom implements CropAspectRatioPresetData {
      @override
      (int, int)? get data => (2, 3);
    
      @override
      String get name => '2x3 (customized)';
    }
  8. Implement custom aspect ratio presets

    master

    To define a custom aspect ratio for the cropper, implement the CropAspectRatioPresetData interface. You must override the data getter, which returns a tuple of (int, int)? representing the width and height ratio, and the name getter, which returns a String label for the preset.

    Note for iOS: The iOS implementation only supports a single custom aspect ratio in the preset list.

    class CropAspectRatioPresetCustom implements CropAspectRatioPresetData {
      @override
      (int, int)? get data => (2, 3);
    
      @override
      String get name => '2x3 (customized)';
    }
  9. Configure WebUiSettings for the web implementation

    master

    The WebUiSettings object allows you to customize the appearance and behavior of the cropper when running in a web browser.

    Key configuration areas include:

    • Presentation Style: Use presentStyle to choose between WebPresentStyle.page (navigates to a new page) or WebPresentStyle.dialog (shows a modal dialog).
    • Sizing: Set the size property to define the dimensions of the cropper container.
    • UI Customization: Customize translations, themeData, and barrierColor (for dialog mode).
    • Custom Builders: You can override the default UI by providing customRouteBuilder (for page mode) or customDialogBuilder (for dialog mode). These builders receive the following callbacks:
      • initializer: A function to initialize the cropper.
      • doCrop: A function to trigger the cropping process.
      • doRotate: A function to rotate the image.
      • doScale: A function to scale the image.
  10. Customize iOS UI with IOUiSettings

    master

    To customize the iOS user interface (which uses the TOCropViewController library), use the IOUiSettings helper class.

    Key customization options include:

    • Rect/Initial State: minimumAspectRatio, rectX, rectY, rectWidth, and rectHeight.
    • Dialog/Navigation: showActivitySheetOnDone, showCancelConfirmationDialog, embedInNavigationController, and hidesNavigationBar.
    • Toolbar Buttons: rotateClockwiseButtonHidden, rotateButtonsHidden, resetButtonHidden, aspectRatioPickerButtonHidden, and resetAspectRatioEnabled.
    • Aspect Ratio: aspectRatioLockDimensionSwapEnabled (swaps dimensions based on orientation) and aspectRatioLockEnabled.
    • Text/Style: title, doneButtonTitle, cancelButtonTitle, cropStyle (rectangle or circle), and aspectRatioPresets.
    // Example of IOUiSettings properties
    IOUiSettings(
      title: 'iOS Cropper',
      aspectRatioLockEnabled: true,
      cropStyle: CropStyle.rectangle,
      // ... other properties
    )
  11. Customize Web UI with WebUiSettings

    master

    To customize the Web user interface (which uses the cropperjs library), use the WebUiSettings helper class.

    Key customization options include:

    • Display: size (CropperSize), viewwMode (WebViewMode), dragMode (WebDragMode), modal, guides, center, highlight, background, and presentStyle (WebPresentStyle).
    • Interactivity: movable, rotatable, scalable, zoomable, zoomOnTouch, zoomOnWheel, cropBoxMovable, cropBoxResizable, and toggleDragModeOnDblclick.
    • Constraints: minContainerWidth, minContainerHeight, minCropBoxWidth, and minCropBoxHeight.
    • Customization: customDialogBuilder and customRouteBuilder for overriding the default dialog or route behavior.
    • Theming: barrierColor and themeData.