Simple image crop library for iOS

Related tags

Image PhotoCropper
Overview

PhotoCropper

Platform Language: Swift 5 SwiftPM compatible CocoaPods compatible Version License

This is a simple image crop library for iOS I made for fun on Christmas πŸŽ… πŸŽ„ based on RxSwift,

which doesn't support customized resizing by users.

This would be appropriate when limiting crop rate control to users.

Preview

Preview

Requirements

  • Swift 5

  • iOS 10.0 +

  • RxSwift 6.0

  • RxCocoa 6.0

  • RxGesture 4.0

  • SnapKit 5.0

  • Then 2.0

Installation

CocoaPods

PhotoCropper is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'PhotoCropper'
$ pod install

Swift Package Manager(SPM)

In Xcode, add as Swift package with this URL: https://github.com/aaronLab/PhotoCropper

Usage

  1. Import PhotoCropper on top of your view controller file.

  2. ⚠️ If you want to change the ratio or some configurations, you can change the values in viewDidLoad by the singleton instance called PhotoCropper "before you initialize the PhotoCropperView." For more information, please check the example files.

  3. Create a view using PhotoCropperView(with:) in a view controller.

  4. Make constraints of the PhotoCropperView you made in the view controller.

  5. Subscribe the resultImage: PublishSubject<UIImage?> in the PhotoCropperView you declared and when the subjec emits the result image, you can go with that.

  6. To change the ratio, use PhotoCropper.shared.ratio: BehaviorRelay<CGFloat> like below.

    • e.g. PhotoCropper.shared.ratio.accept(2 / 3)
    • 2 / 3 means 2:3 ratio of the size.
  7. Now you can crop the image using PhtoCropperView.crop: PublishSubject<Void>

    • To do this, you can bind a button or send a signal manually like this: PhotoCropoerVirw.crop.onNext(())

Customization

PhotoCropper

A singleton configuration instance.

⚠️ You should change the values before you initialize the view except the ratio and cornerRadius whose type is BehaviorRelay<CGFloat>.

You can change the valuse like this: PhotoCropper.shared.<PROPERTY_NAME>

/// The crop ratio
public var ratio: BehaviorRelay<CGFloat> { get }

/// Defines the `max zoom scale multiplier` by the `minZoomScale`
///
/// Default value is `5.0`
public var maxZoomScaleMultiplier: CGFloat

/// Hide grid
///
/// Default value is `false`
public var hideGrid: Boo

/// Hide frame border
///
/// Default value is `false`
public var hideFrameBorder: Bool

/// Hide the overlay views on the image
///
/// Default value is `false`
public var hideOverlay: Bool

/// Appearance
public var appearance: PhotoCropperAppearance

/// Defines the transition duration.
///
/// The default value is `0.25`
public var transitionDuration: CGFloat

/// Defines the animation duration.
///
/// The default value is `0.3`
public var animationDuration: CGFloat

/// Grid hide delay duration
///
/// - This defines the duration of when the grid will be hidden after user interaction done.
///
/// Default duration is `0.3`
public var gridHideDelayDuration: TimeInterval

/// Number of the grid lines
///
/// The number of the grid lines in the frame by each orientation.
///
/// Default duration is `3`
public var numberOfGridLines

PhotoCropperAppearance

Appearance configurations.

You can change the values from PhotoCropper singleton instance.

PhotoCropper.shared.appearance.<PROPERTY_NAME>

/// Corner radius of the frame.
///
/// Default value is `0`
public var cornerRadius: BehaviorRelay<CGFloat>

/// The color of `frame`.
///
/// Default value is `.white`
public var frameColor: UIColor

/// The color of `grid`.
///
/// Default value is `.white`
public var gridColor: UIColor

/// The color of the overlay for the image out of the frame.
///
/// Default value is `.black.withAlphaComponent(0.6)`
public var overlayColor: UIColor

/// The frame border width
///
/// Default value is `2.0`
public var frameBorderWidth: CGFloat

/// The grid width
///
/// Default value is `1.0`
public var gridWidth: CGFloat

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

//
//  ViewController.swift
//  PhotoCropper
//
//  Created by Aaron Lee on 12/26/2021.
//  Copyright (c) 2021 Aaron Lee. All rights reserved.
//

import UIKit
import RxCocoa
import RxGesture
import RxSwift
import SnapKit
import Then
import PhotoCropper

class ViewController: UIViewController {

  private var bag = DisposeBag()

  private var doneButton = UIBarButtonItem(barButtonSystemItem: .done,
                                           target: nil,
                                           action: nil)

  private var photoCropperView = PhotoCropperView(with: UIImage(named: "image"))

  private var stackView = UIStackView()
    .then {
      $0.axis = .vertical
      $0.spacing = 8
      $0.distribution = .fill
      $0.alignment = .fill
    }

  private var orientationSegmentedControl = UISegmentedControl(
    items: Orientation.allCases.map { $0.rawValue }
  )

  private var ratioSegmentedControl = UISegmentedControl(
    items: Ratio.allCases.map { $0.description(by: .landscape) }
  )

  override func viewDidLoad() {
    super.viewDidLoad()

    configureView()
    layoutView()
    bindRx()
  }

}

// MARK: - Configure

extension ViewController {

  private func configureView() {
    title = "PhotoCropper Example"
    navigationItem.rightBarButtonItem = doneButton

    if #available(iOS 13.0, *) {
      view.backgroundColor = .systemBackground
    } else {
      view.backgroundColor = .white
    }
  }

}

// MARK: - Layout

extension ViewController {

  private func layoutView() {
    view.addSubview(photoCropperView)
    view.addSubview(stackView)

    layoutPhotoCropperView()
    layoutStackView()
    layoutSegmentedControls()
  }

  private func layoutPhotoCropperView() {
    photoCropperView.snp.makeConstraints {
      $0.top.leading.equalTo(view.safeAreaLayoutGuide)
      $0.trailing.equalTo(view.safeAreaLayoutGuide)
      $0.bottom.equalTo(stackView.snp.top)
    }
  }

  private func layoutStackView() {

    stackView.snp.makeConstraints {
      $0.leading.equalTo(view.safeAreaLayoutGuide).offset(16)
      $0.trailing.bottom.equalTo(view.safeAreaLayoutGuide).offset(-16)
    }
  }

  private func layoutSegmentedControls() {
    [orientationSegmentedControl, ratioSegmentedControl].forEach {
      $0.selectedSegmentIndex = 0
      stackView.addArrangedSubview($0)
      $0.snp.makeConstraints {
        $0.height.equalTo(30)
      }
    }
  }

}

// MARK: - Bind

extension ViewController {

  private func bindRx() {
    bindInput()
    bindOutput()
  }

}

// MARK: - Input

extension ViewController {

  private func bindInput() {
    bindDoneButton()
    bindOrientationSegmentedControlSelectedIndex()
    bindRatioSegmentedControlSelectedIndex()
  }

  private func bindDoneButton() {
    doneButton.rx.tap
      .bind(to: photoCropperView.crop)
      .disposed(by: bag)
  }

  private func bindOrientationSegmentedControlSelectedIndex(){
    orientationSegmentedControl
      .rx
      .selectedSegmentIndex
      .skip(1)
      .map { [weak self] index -> CGFloat in
        guard let self = self else { return 1 }
        let orientation = Orientation.allCases[index]
        let ratio = Ratio.allCases[self.ratioSegmentedControl.selectedSegmentIndex]
        let ratioValue = ratio.ratio(by: orientation)
        return ratioValue
      }
      .bind(to: PhotoCropper.shared.ratio)
      .disposed(by: bag)
  }

  private func bindRatioSegmentedControlSelectedIndex() {
    ratioSegmentedControl
      .rx
      .selectedSegmentIndex
      .skip(1)
      .map { [weak self] index -> CGFloat in
        guard let self = self else { return 1 }
        let orientation = Orientation.allCases[self.orientationSegmentedControl.selectedSegmentIndex]
        let ratio = Ratio.allCases[index]
        let ratioValue = ratio.ratio(by: orientation)
        return ratioValue
      }
      .bind(to: PhotoCropper.shared.ratio)
      .disposed(by: bag)
  }

}

// MARK: - Output

extension ViewController {

  private func bindOutput() {
    photoCropperView.resultImage
      .subscribe(onNext: { [weak self] image in
        guard let self = self else { return }

        let vc = ResultImageViewController()
        vc.imageView.image = image
        self.navigationController?.pushViewController(vc, animated: true)
      })
      .disposed(by: bag)
  }

}

Author

Aaron Lee, [email protected]

License

PhotoCropper is available under the MIT license. See the LICENSE file for more info.

You might also like...
Twitter Image Pipeline is a robust and performant image loading and caching framework for iOS clients

Twitter Image Pipeline (a.k.a. TIP) Background The Twitter Image Pipeline is a streamlined framework for fetching and storing images in an application

Image-cropper - Image cropper for iOS

Image-cropper Example To run the example project, clone the repo, and run pod in

πŸ“· A composable image editor using Core Image and Metal.
πŸ“· A composable image editor using Core Image and Metal.

Brightroom - Composable image editor - building your own UI Classic Image Editor PhotosCrop Face detection Masking component πŸŽ‰ v2.0.0-alpha now open!

πŸ“· A composable image editor using Core Image and Metal.
πŸ“· A composable image editor using Core Image and Metal.

Brightroom - Composable image editor - building your own UI Classic Image Editor PhotosCrop Face detection Masking component πŸŽ‰ v2.0.0-alpha now open!

A complete Mac App: drag an image file to the top section and the bottom section will show you the text of any QRCodes in the image.

QRDecode A complete Mac App: drag an image file to the top section and the bottom section will show you the text of any QRCodes in the image. QRDecode

Convert the image to hexadecimal to send the image to e-paper

ConvertImageToHex Convert the image to hexadecimal to send the image to e-paper Conversion Order // 0. hex둜 λ³€ν™˜ν•  이미지 var image = UIImage(named: "sample

An instagram-like image editor that can apply preset filters passed to it and customized editings to a binded image.
An instagram-like image editor that can apply preset filters passed to it and customized editings to a binded image.

CZImageEditor CZImageEditor is an instagram-like image editor with clean and intuitive UI. It is pure swift and can apply preset filters and customize

PhotoRow - Simple image row based on Eureka for iOS

PhotoRow Simple image row based on Eureka for iOS. Since source type photoLibrar

Swift Image Slider library for iOS

Banana - ImageSlider for Swift Image slider with very simple interface. At a Glance @IBOutlet weak var imageScrollView: UIScrollView! // Here imageArr

Releases(0.2.0)
Owner
Aaron Lee
My mother tongue is Swift.
Aaron Lee
βœ‚οΈ Detect and crop faces, barcodes and texts in image with iOS 11 Vision api.

ImageDetect ImageDetect is a library developed on Swift. With ImageDetect you can easily detect and crop faces, texts or barcodes in your image with i

Arthur Sahakyan 299 Dec 17, 2022
Image picker with custom crop rect for iOS written in Swift (Ported over from GKImagePicker)

WDImagePicker Ever wanted a custom crop area for the UIImagePickerController? Now you can have it with WDImagePicker. Just set your custom crop area a

Wu Di 96 Dec 19, 2022
Crop faces, inside of your image, with iOS 11 Vision api.

FaceCropper Requirements Xcode 9.0 (beta) or higher. iOS 11.0 (beta) or higher. (It is possible to import this library under the iOS 11. But it won't

Taejun Kim 488 Dec 17, 2022
ZImageCropper is a simplest way to crop image to any shapes you like.

ZImageCropper ZImageCropper is a simplest way to crop image to any shapes you like. Example To run the example project, clone the repo, and run pod in

Mohammad Zaid Pathan 219 Dec 17, 2022
A crop, compression, resize and trimming library for videos, based on AVKit.

VideoKit VideoKit is a high level layer on top of AVKit How it works // With this config, the video will get resized to 1920x1080p, the maximal length

Knoggl 9 Dec 24, 2022
A view controller for iOS that allows users to crop portions of UIImage objects

TOCropViewController TOCropViewController is an open-source UIViewController subclass to crop out sections of UIImage objects, as well as perform basi

Tim Oliver 4.4k Jan 1, 2023
Autocrop - A face-aware crop utility using OSX's Vision framework

autocrop A high-performance face-aware crop utility using OSX's Vision framework

Alex Dong 0 Jan 19, 2022
AYImageKit is a Swift Library for Async Image Downloading, Show Name's Initials and Can View image in Separate Screen.

AYImageKit AYImageKit is a Swift Library for Async Image Downloading. Features Async Image Downloading. Can Show Text Initials. Can have Custom Styles

Adnan Yousaf 11 Jan 10, 2022
An image download extension of the image view written in Swift for iOS, tvOS and macOS.

Moa, an image downloader written in Swift for iOS, tvOS and macOS Moa is an image download library written in Swift. It allows to download and show an

Evgenii Neumerzhitckii 330 Sep 9, 2022
AsyncImage before iOS 15. Lightweight, pure SwiftUI Image view, that displays an image downloaded from URL, with auxiliary views and local cache.

URLImage URLImage is a SwiftUI view that displays an image downloaded from provided URL. URLImage manages downloading remote image and caching it loca

Dmytro Anokhin 1k Jan 4, 2023