Agrume - πŸ‹ An iOS image viewer written in Swift with support for multiple images.

Overview

Agrume

Build Status Carthage compatible Version License Platform SPM

An iOS image viewer written in Swift with support for multiple images.

Agrume

Requirements

  • Swift 5.0
  • iOS 9.0+
  • Xcode 10.2+

Installation

Use Swift Package Manager.

Or CocoaPods. Add the dependency to your Podfile and then run pod install:

pod "Agrume"

Or Carthage. Add the dependency to your Cartfile and then run carthage update:

github "JanGorman/Agrume"

Usage

There are multiple ways you can use the image viewer (and the included sample project shows them all).

For just a single image it's as easy as

Basic

import Agrume

private lazy var agrume = Agrume(image: UIImage(named: "…")!)

@IBAction func openImage(_ sender: Any) {
  agrume.show(from: self)
}

You can also pass in a URL and Agrume will take care of the download for you.

Background Configuration

Agrume has different background configurations. You can have it blur the view it's covering or supply a background color:

let agrume = Agrume(image: UIImage(named: "…")!, background: .blurred(.regular))
// or
let agrume = Agrume(image: UIImage(named: "…")!, background: .colored(.green))

Multiple Images

If you're displaying a UICollectionView and want to add support for zooming, you can also call Agrume with an array of either images or URLs.

// In case of an array of [UIImage]:
let agrume = Agrume(images: images, startIndex: indexPath.item, background: .blurred(.light))
// Or an array of [URL]:
// let agrume = Agrume(urls: urls, startIndex: indexPath.item, background: .blurred(.light))

agrume.didScroll = { [unowned self] index in
  self.collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: [], animated: false)
}
agrume.show(from: self)

This shows a way of keeping the zoomed library and the one in the background synced.

Animated gifs

Agrume bundles SwiftyGif to display animated gifs. You use SwiftyGif's custom UIImage initializer:

let image = UIImage(gifName: "animated.gif")
let agrume = Agrume(image: image)
agrume.display(from: self)

// Or gif using data:

let image = UIImage(gifData: data)
let agrume = Agrume(image: image)

// Or multiple images:

let images = [UIImage(gifName: "animated.gif"), UIImage(named: "foo.png")] // You can pass both animated and regular images at the same time
let agrume = Agrume(images: images)

Remote animated gifs (i.e. using the url or urls initializer) are supported. Agrume does the image type detection and displays them properly. If using Agrume from a custom UIImageView you may need to rebuild the UIImage using the original data to preserve animation vs. using the UIImage instance from the image view.

Close Button

Per default you dismiss the zoomed view by dragging/flicking the image off screen. You can opt out of this behaviour and instead display a close button. To match the look and feel of your app you can pass in a custom UIBarButtonItem:

// Default button that displays NSLocalizedString("Close", …)
let agrume = Agrume(image: UIImage(named: "…")!, .dismissal: .withButton(nil))
// Customise the button any way you like. For example display a system "x" button
let button = UIBarButtonItem(barButtonSystemItem: .stop, target: nil, action: nil)
button.tintColor = .red
let agrume = Agrume(image: UIImage(named: "…")!, .dismissal: .withButton(button))

The included sample app shows both cases for reference.

Custom Download Handler

If you want to take control of downloading images (e.g. for caching), you can also set a download closure that calls back to Agrume to set the image. For example, let's use MapleBacon.

import Agrume
import MapleBacon

private lazy var agrume = Agrume(url: URL(string: "https://dl.dropboxusercontent.com/u/512759/MapleBacon.png")!)

@IBAction func openURL(_ sender: Any) {
  agrume.download = { url, completion in
    Downloader.default.download(url) { image in
      completion(image)
    }
  }
  agrume.show(from: self)
}

Global Custom Download Handler

Instead of having to define a handler on a per instance basis you can instead set a handler on the AgrumeServiceLocator. Agrume will use this handler for all downloads unless overriden on an instance as described above:

import Agrume

AgrumeServiceLocator.shared.setDownloadHandler { url, completion in
  // Download data, cache it and call the completion with the resulting UIImage
}

// Some other place
agrume.show(from: self)

Custom Data Source

For more dynamic library needs you can implement the AgrumeDataSource protocol that supplies images to Agrume. Agrume will query the data source for the number of images and if that number changes, reload it's scrolling image view.

import Agrume

let dataSource: AgrumeDataSource = MyDataSourceImplementation()
let agrume = Agrume(dataSource: dataSource)

agrume.show(from: self)

Status Bar Appearance

You can customize the status bar appearance when displaying the zoomed in view. Agrume has a statusBarStyle property:

let agrume = Agrume(image: image)
agrume.statusBarStyle = .lightContent
agrume.show(from: self)

Long Press Gesture and Downloading Images

If you want to handle long press gestures on the images, there is an optional onLongPress closure. This will pass an optional UIImage and a reference to the Agrume UIViewController as parameters. The project includes a helper class to easily opt into downloading the image to the user's photo library called AgrumePhotoLibraryHelper. First, create an instance of the helper:

private func makeHelper() -> AgrumePhotoLibraryHelper {
  let saveButtonTitle = NSLocalizedString("Save Photo", comment: "Save Photo")
  let cancelButtonTitle = NSLocalizedString("Cancel", comment: "Cancel")
  let helper = AgrumePhotoLibraryHelper(saveButtonTitle: saveButtonTitle, cancelButtonTitle: cancelButtonTitle) { error in
    guard error == nil else {
      print("Could not save your photo")
      return
    }
    print("Photo has been saved to your library")
  }
  return helper
}

and then pass this helper's long press handler to Agrume as follows:

let helper = makeHelper()
agrume.onLongPress = helper.makeSaveToLibraryLongPressGesture

Custom Overlay View

You can customise the look and functionality of the image views. To do so, you need create a class that inherits from AgrumeOverlayView: UIView. As this is nothing more than a regular UIView you can do anything you want with it like add a custom toolbar or buttons to it. The example app shows a detailed example of how this can be achieved.

Lifecycle

Agrume offers the following lifecycle closures that you can optionally set:

  • willDismiss
  • didDismiss
  • didScroll

Running the Sample Code

The project ships with an example app that shows the different functions documented above. Since there is a dependency on SwiftyGif you will also need to fetch that to run the project. It's included as git submodule. After fetching the repository, from the project's root directory run:

git submodule update --init

Licence

Agrume is released under the MIT license. See LICENSE for details

Comments
  • Flicker after closing the expanded image

    Flicker after closing the expanded image

    Really love this library! I am having a small issue when closing images. Would love to get your thoughts on what the issue might be.

    I get a little flicker after the image I tap is closed. I have included a video here.

    The image is in a scrollview. Untitled.zip

    opened by nevinjethmalani 19
  • The image is not centered

    The image is not centered

    I’m using Agrume to display an image on my swift application. But the image is not centered. I have to click in order to bring it to the center. It is located to the left and when I click it goes to the center. I’m displaying a single image. Could you please help me? Thank you

    stale 
    opened by meme17sk 11
  • added savePhotoOnLongPress function

    added savePhotoOnLongPress function

    Created this function so that users can easily use a simple default UIAlertController with two options: Save Photo and Cancel

    using it in just one single line: agrume.onLongPress = agrume.photoSavedToLibrary

    I didnt add it as a default longPress function because some user's might not want this and also they might have not have NSPhotoLibraryUsageDescription and NSPhotoLibraryAddUsageDescription in their info.plist.

    @JanGorman Tell me what you think about this. If it needs some change or any suggestion how to improve.

    I was thinking to add some documentation in the readme after this gets merged to master πŸ‘

    opened by alexookah 11
  • hideStatusBar not working

    hideStatusBar not working

    I see there is a hideStatusBar, but from my side, it seems like it's not working, since the status bar is still present. Anything I am missing?

                let agrume = Agrume(image: image, backgroundBlurStyle: .dark)
                agrume.hideStatusBar = true
                agrume.showFrom(topViewController)
    
    opened by allaire 9
  • Add long press gesture & updateImage func

    Add long press gesture & updateImage func

    So client can e.g. show an action sheet upon long press.

    Added updateImage function so we could refresh Agrume cells after the image got changed e.g. from cropping it

    opened by hyouuu 8
  • Page dot indicator

    Page dot indicator

    Currently doesn't seem to support this feature, and I might get time in the future to make it, but wanted to throw it out here first - any thoughts or existing approaches?

    enhancement stale 
    opened by hyouuu 8
  • Custom data source problem

    Custom data source problem

    Hello,

    I am trying to use custom data source for loading images from photo library. Here is my data source implementation:

    class AssetDataSource: AgrumeDataSource {
    
        var numberOfImages: Int
        var urls: [URL]
    
        init(urls: [URL]) {
            self.urls = urls
            self.numberOfImages = urls.count
        }
    
        func image(forIndex index: Int, completion: @escaping (UIImage?) -> Void) {
            let assets = PHAsset.fetchAssets(withALAssetURLs: urls, options: nil)
    
            let imageManager = PHCachingImageManager()
            let imageRequestOptions = PHImageRequestOptions()
            imageRequestOptions.isNetworkAccessAllowed = true
            imageRequestOptions.isSynchronous = true
    
            imageManager.requestImage(for: assets[index], targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: imageRequestOptions) { image, _ in
                completion(image)
            }
        }
    
    }
    

    And I'm using it like this:

    let dataSource: AgrumeDataSource = AssetDataSource(urls: imageUrls)
    let agrume = Agrume(dataSource: dataSource, startIndex: index, background: .blurred(.light))
    agrume.show(from: self)
    

    But it falls into an infinite loop in this init function.

    public convenience init(dataSource: AgrumeDataSource, startIndex: Int = 0, background: Background = .colored(.black)) {
         self.init(dataSource: dataSource, startIndex: startIndex, background: background)
    }
    

    Is this the right way to use Custom Data Source? Or is this a bug with library? Thank you in advance.

    opened by mdilaveroglu 8
  • Cannot find type 'Agrume' in scope

    Cannot find type 'Agrume' in scope

    got this crash in agrume.swift

    Printing description of self: expression produced error: error: /var/folders/yh/2x5wsjps5n1byqbhl95h_rmm0000gn/T/expr30-1e0641..swift:1:65: error: cannot find type 'Agrume' in scope Swift._DebuggerSupport.stringForPrintObject(Swift.UnsafePointer<Agrume.Agrume>(bitPattern: 0x10d02ca60)!.pointee)

    @JanGorman please help me for resolve this crash.. Screenshot 2020-11-24 at 12 38 22 PM

    stale 
    opened by gouravideal 7
  • Problem with Agrume on Bitrise's testing step

    Problem with Agrume on Bitrise's testing step

    I have an app (legacy code) which uses Agrume 5.3.0. When I build it on my Xcode and run tests on it, everything works just fine. But when I try to run my workflow on Bitrise, it gives me this error on the testing step:

    ** TEST BUILD FAILED **
    
    
    The following build commands failed:
    	CompileSwift normal arm64 /Users/vagrant/git/K2KonnectApp/Pods/Agrume/Agrume/Agrume.swift
    	CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler
    

    All targets of the project use Swift 4 and, inside my Podfile, there is this code:

    post_install do |installer|
        installer.pods_project.targets.each do |target|
            if ['EPContactsPicker', 'SWXMLHash'].include? target.name
                target.build_configurations.each do |config|
                    config.build_settings['SWIFT_VERSION'] = '4.0'
                end
            end
            if ['Splitflap', 'Agrume', 'SwiftyGif', 'FoldingCell', 'UICircularProgressRing'].include? target.name
                target.build_configurations.each do |config|
                    config.build_settings['SWIFT_VERSION'] = '4.2'
                end
            end
        end
    end
    

    Can you help me figure it out?

    opened by mateszbueno 7
  • Image not loading fully

    Image not loading fully

    opened by nishan-p 7
  • Double Tap Zoom Problems

    Double Tap Zoom Problems

    Hi, I notice that depending on the image, when I double tap to zoom, sometimes the whole image scrolls off the screen when it zooms in. For example, a wide image on a device in portrait orientation is one situation.

    In looking at the func doubleTap in AgrumeCell.swift to examine the problem, I notice some code computing targetZoom that appears inconsistent and I believe this is the cause of the problems.

    For example, you're using the zoomWidth in a calculation for height. And you are doing division rather than subtraction in another part. Not sure which is correct, but they are inconsistent. Also, the else part has the same inconsistent code.

    I have been experimenting with changing this code around and have made a version that appears to function a little better than what's in the repo, but as I don't fully understand what the code is trying to do, it would probably be better if the author looked at making fixes.

    opened by DavidLari 7
Releases(5.8.6)
Owner
Jan Gorman
Software Engineering @alan-eu. Also compiling Swift source files.
Jan Gorman
Image slide-show viewer with multiple predefined transition styles, with ability to create new transitions with ease.

ATGMediaBrowser ATGMediaBrowser is an image slide-show viewer that supports multiple predefined transition styles, and also allows the client to defin

null 200 Dec 19, 2022
DTPhotoViewerController - A fully customizable photo viewer ViewController to display single photo or collection of photos, inspired by Facebook photo viewer.

DTPhotoViewerController Example Demo video: https://youtu.be/aTLx4M4zsKk DTPhotoViewerController is very simple to use, if you want to display only on

Tung Vo 277 Dec 17, 2022
Photo Browser / Viewer inspired by Facebook's and Tweetbot's with ARC support, swipe-to-dismiss, image progress and more

IDMPhotoBrowser IDMPhotoBrowser is a new implementation based on MWPhotoBrowser. We've added both user experience and technical features inspired by F

Thiago Peres 2.7k Dec 21, 2022
add text(multiple line support) to imageView, edit, rotate or resize them as you want, then render the text on image

StickerTextView is an subclass of UIImageView. You can add multiple text to it, edit, rotate, resize the text as you want with one finger, then render the text on Image.

Textcat 478 Dec 17, 2022
Lightbox is a convenient and easy to use image viewer for your iOS app

Lightbox is a convenient and easy to use image viewer for your iOS app, packed with all the features you expect: Paginated image slideshow. V

HyperRedink 1.5k Dec 22, 2022
Swift image slideshow with circular scrolling, timer and full screen viewer

?? ImageSlideshow Customizable Swift image slideshow with circular scrolling, timer and full screen viewer ?? Example To run the example project, clon

Petr Zvoníček 1.7k Dec 21, 2022
An image viewer Γ  la Twitter

For the latest changes see the CHANGELOG Install CocoaPods pod 'ImageViewer' Carthage github "Krisiacik/ImageViewer" Sample Usage For a detailed examp

Kristian Angyal 2.4k Dec 29, 2022
A snappy image viewer with zoom and interactive dismissal transition.

A snappy image viewer with zoom and interactive dismissal transition. Features Double tap to zoom in/out Interactive dismissal transition Animate in f

Lucas 421 Dec 1, 2022
Slide image viewer library similar to Twitter and LINE.

Overview You can use it simply by passing the necessary information! Serrata is a UI library that allows you to intuitively view images. Features King

Takuma Horiuchi 324 Dec 9, 2022
A snappy image viewer with zoom and interactive dismissal transition.

A snappy image viewer with zoom and interactive dismissal transition. Features Double tap to zoom in/out Interactive dismissal transition Animate in f

Lucas 421 Dec 1, 2022
Simple PhotoBrowser/Viewer inspired by facebook, twitter photo browsers written by swift

SKPhotoBrowser [![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-) Simple PhotoBrowser

keishi suzuki 2.4k Jan 6, 2023
FLImagePicker - A simple image picker supported multiple selection

FLImagePicker A simple image picker supported multiple selection. Features Multiple selection Gesture supported Dark mode Easy modification Installati

Allen Lee 4 Aug 17, 2022
BeatboxiOS - A sample implementation for merging multiple video files and/or image files using AVFoundation

MergeVideos This is a sample implementation for merging multiple video files and

null 3 Oct 24, 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
Jogendra 113 Nov 28, 2022
FlaneurImagePicker is an iOS image picker that allows users to pick images from different sources (ex: user's library, user's camera, Instagram...). It's highly customizable.

FlaneurImagePicker is a highly customizable iOS image picker that allows users to pick images from different sources (ex: device's library, device's c

FlaneurApp 17 Feb 2, 2020
A high-performance image library for downloading, caching, and processing images in Swift.

Features Asynchronous image downloader with priority queuing Advanced memory and database caching using YapDatabase (SQLite) Guarantee of only one ima

Yap Studios 72 Sep 19, 2022
Swift/iOS viewer for photography galleries or portfolios

Swift/iOS viewer for photography galleries or portfolios. The app is intended for photographers who participate in classical photo clubs: a portfolio covers (curated) images that were presented and critiqued within a photo club.

Peter van den Hamer 8 Dec 24, 2022
High Quality Image ScrollView using cropped tiled images.

THTiledImageView Feature ?? THTiledImageView fully support UIScrollView. You can subclass it and use it. ?? Support Async Image Downloading & Caching.

null 28 Oct 28, 2022