Commit 8035e983 authored by huanglu's avatar huanglu

init project

parents
File added
Pod::Spec.new do |s|
s.name = 'iOSPhotoEditor'
s.version = '0.5'
s.summary = 'Photo Editor supports drawing, writing text and adding stickers and emojis'
s.description = <<-DESC
Photo Editor supports drawing, writing text and adding stickers and emojis
with the ability to scale and rotate objects
DESC
s.homepage = 'https://github.com/M-Hamed/photo-editor'
s.license = { :type => 'MIT', :file => 'LICENSE.md' }
s.author = { 'Mohamed Hamed' => 'mohamed.hamed.ibrahem@gmail.com' }
s.source = { :git => 'https://github.com/M-Hamed/photo-editor.git', :tag => s.version.to_s }
s.ios.deployment_target = '9.0'
s.swift_version = '4.2'
s.source_files = "Photo Editor/**/*.{swift}"
s.exclude_files = "Photo Editor/**/AppDelegate.swift"
s.resources = "Photo Editor/**/*.{png,jpeg,jpg,storyboard,xib,ttf}"
end
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:GeekImageEditor.xcodeproj">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>GeekImageEditor.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>2</integer>
</dict>
</dict>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:GeekImageEditor.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
//
// AppDelegate.swift
// GeekImageEditor
//
// Created by wenjindu on 2020/2/20.
// Copyright © 2020 wenjindu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
\ No newline at end of file
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15705" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15706"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="GeekImageEditor" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="hoT-im-Qpj">
<rect key="frame" x="184" y="438" width="46" height="30"/>
<state key="normal" title="Button"/>
<connections>
<action selector="tapBtnAction:" destination="BYZ-38-t0r" eventType="touchUpInside" id="aq6-Gg-M9c"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="hoT-im-Qpj" firstAttribute="centerY" secondItem="6Tk-OE-BBY" secondAttribute="centerY" id="1l2-Ua-S5B"/>
<constraint firstItem="hoT-im-Qpj" firstAttribute="centerX" secondItem="6Tk-OE-BBY" secondAttribute="centerX" id="c8D-P7-Ki2"/>
</constraints>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="139" y="110"/>
</scene>
</scenes>
</document>
//
// ColorCollectionViewCell.swift
// Photo Editor
//
// Created by Mohamed Hamed on 5/1/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
class ColorCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var colorView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
super.layoutSubviews()
colorView.layer.cornerRadius = colorView.frame.width / 2
colorView.clipsToBounds = true
colorView.layer.borderWidth = 1.0
colorView.layer.borderColor = UIColor.white.cgColor
}
override var isSelected: Bool {
didSet {
if isSelected {
let previouTransform = colorView.transform
UIView.animate(withDuration: 0.2,
animations: {
self.colorView.transform = self.colorView.transform.scaledBy(x: 1.3, y: 1.3)
},
completion: { _ in
UIView.animate(withDuration: 0.2) {
self.colorView.transform = previouTransform
}
})
} else {
// animate deselection
}
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14113" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="ColorCollectionViewCell" id="gTV-IL-0wX" customClass="ColorCollectionViewCell" customModule="iOSPhotoEditor" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="100" height="100"/>
<autoresizingMask key="autoresizingMask"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
<rect key="frame" x="0.0" y="0.0" width="100" height="100"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="ncL-uU-y1P">
<rect key="frame" x="40" y="40" width="20" height="20"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="height" constant="20" id="1NF-oX-6Ag"/>
<constraint firstAttribute="width" constant="20" id="LcG-gU-6ME"/>
</constraints>
</view>
</subviews>
</view>
<constraints>
<constraint firstItem="ncL-uU-y1P" firstAttribute="centerY" secondItem="gTV-IL-0wX" secondAttribute="centerY" id="1QZ-sk-wr6"/>
<constraint firstItem="ncL-uU-y1P" firstAttribute="centerX" secondItem="gTV-IL-0wX" secondAttribute="centerX" id="8F5-g3-Cfh"/>
</constraints>
<viewLayoutGuide key="safeArea" id="qgJ-qn-S9q"/>
<size key="customSize" width="100" height="99"/>
<connections>
<outlet property="colorView" destination="ncL-uU-y1P" id="7PV-0E-mnW"/>
</connections>
<point key="canvasLocation" x="59" y="78"/>
</collectionViewCell>
</objects>
</document>
//
// ColorsCollectionViewDelegate.swift
// Photo Editor
//
// Created by Mohamed Hamed on 5/1/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
class ColorsCollectionViewDelegate: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var colorDelegate : ColorDelegate?
/**
Array of Colors that will show while drawing or typing
*/
var colors = [UIColor.black,
UIColor.darkGray,
UIColor.gray,
UIColor.lightGray,
UIColor.white,
UIColor.blue,
UIColor.green,
UIColor.red,
UIColor.yellow,
UIColor.orange,
UIColor.purple,
UIColor.cyan,
UIColor.brown,
UIColor.magenta]
override init() {
super.init()
}
var stickersViewControllerDelegate : StickersViewControllerDelegate?
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colors.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
colorDelegate?.didSelectColor(color: colors[indexPath.item])
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColorCollectionViewCell", for: indexPath) as! ColorCollectionViewCell
cell.colorView.backgroundColor = colors[indexPath.item]
return cell
}
}
This diff is collapsed.
This diff is collapsed.
//
// CropViewController.swift
// CropViewController
//
// Created by Guilherme Moura on 2/25/16.
// Copyright © 2016 Reefactor, Inc. All rights reserved.
// Credit https://github.com/sprint84/PhotoCropEditor
import UIKit
public protocol CropViewControllerDelegate: class {
func cropViewController(_ controller: CropViewController, didFinishCroppingImage image: UIImage, transform: CGAffineTransform, cropRect: CGRect)
func cropViewControllerDidCancel(_ controller: CropViewController)
}
open class CropViewController: UIViewController {
open weak var delegate: CropViewControllerDelegate?
open var image: UIImage? {
didSet {
cropView?.image = image
}
}
open var keepAspectRatio = false {
didSet {
cropView?.keepAspectRatio = keepAspectRatio
}
}
open var cropAspectRatio: CGFloat = 0.0 {
didSet {
cropView?.cropAspectRatio = cropAspectRatio
}
}
open var cropRect = CGRect.zero {
didSet {
adjustCropRect()
}
}
open var imageCropRect = CGRect.zero {
didSet {
cropView?.imageCropRect = imageCropRect
}
}
open var toolbarHidden = false
open var rotationEnabled = false {
didSet {
cropView?.rotationGestureRecognizer.isEnabled = rotationEnabled
}
}
open var rotationTransform: CGAffineTransform {
return cropView!.rotation
}
open var zoomedCropRect: CGRect {
return cropView!.zoomedCropRect()
}
fileprivate var cropView: CropView?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initialize()
}
fileprivate func initialize() {
rotationEnabled = true
}
open override func loadView() {
let contentView = UIView()
contentView.autoresizingMask = .flexibleWidth
contentView.backgroundColor = UIColor.black
view = contentView
// Add CropView
cropView = CropView(frame: contentView.bounds)
contentView.addSubview(cropView!)
}
open override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.isTranslucent = false
navigationController?.toolbar.isTranslucent = false
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(CropViewController.cancel(_:)))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(CropViewController.done(_:)))
// if self.toolbarItems == nil {
// let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
// let constrainButton = UIBarButtonItem(title: "Constrain", style: .plain, target: self, action: #selector(CropViewController.constrain(_:)))
// toolbarItems = [flexibleSpace, constrainButton, flexibleSpace]
// }
//
// navigationController?.isToolbarHidden = toolbarHidden
cropView?.image = image
cropView?.rotationGestureRecognizer.isEnabled = rotationEnabled
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if cropAspectRatio != 0 {
cropView?.cropAspectRatio = cropAspectRatio
}
if !cropRect.equalTo(CGRect.zero) {
adjustCropRect()
}
if !imageCropRect.equalTo(CGRect.zero) {
cropView?.imageCropRect = imageCropRect
}
cropView?.keepAspectRatio = keepAspectRatio
}
open func resetCropRect() {
cropView?.resetCropRect()
}
open func resetCropRectAnimated(_ animated: Bool) {
cropView?.resetCropRectAnimated(animated)
}
@objc func cancel(_ sender: UIBarButtonItem) {
delegate?.cropViewControllerDidCancel(self)
}
@objc func done(_ sender: UIBarButtonItem) {
if let image = cropView?.croppedImage {
guard let rotation = cropView?.rotation else {
return
}
guard let rect = cropView?.zoomedCropRect() else {
return
}
delegate?.cropViewController(self, didFinishCroppingImage: image, transform: rotation, cropRect: rect)
}
}
@objc func constrain(_ sender: UIBarButtonItem) {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let original = UIAlertAction(title: "Original", style: .default) { [unowned self] action in
guard let image = self.cropView?.image else {
return
}
guard var cropRect = self.cropView?.cropRect else {
return
}
let width = image.size.width
let height = image.size.height
let ratio: CGFloat
if width < height {
ratio = width / height
cropRect.size = CGSize(width: cropRect.height * ratio, height: cropRect.height)
} else {
ratio = height / width
cropRect.size = CGSize(width: cropRect.width, height: cropRect.width * ratio)
}
self.cropView?.cropRect = cropRect
}
actionSheet.addAction(original)
let square = UIAlertAction(title: "Square", style: .default) { [unowned self] action in
let ratio: CGFloat = 1.0
// self.cropView?.cropAspectRatio = ratio
if var cropRect = self.cropView?.cropRect {
let width = cropRect.width
cropRect.size = CGSize(width: width, height: width * ratio)
self.cropView?.cropRect = cropRect
}
}
actionSheet.addAction(square)
let threeByTwo = UIAlertAction(title: "3 x 2", style: .default) { [unowned self] action in
self.cropView?.cropAspectRatio = 2.0 / 3.0
}
actionSheet.addAction(threeByTwo)
let threeByFive = UIAlertAction(title: "3 x 5", style: .default) { [unowned self] action in
self.cropView?.cropAspectRatio = 3.0 / 5.0
}
actionSheet.addAction(threeByFive)
let fourByThree = UIAlertAction(title: "4 x 3", style: .default) { [unowned self] action in
let ratio: CGFloat = 3.0 / 4.0
if var cropRect = self.cropView?.cropRect {
let width = cropRect.width
cropRect.size = CGSize(width: width, height: width * ratio)
self.cropView?.cropRect = cropRect
}
}
actionSheet.addAction(fourByThree)
let fourBySix = UIAlertAction(title: "4 x 6", style: .default) { [unowned self] action in
self.cropView?.cropAspectRatio = 4.0 / 6.0
}
actionSheet.addAction(fourBySix)
let fiveBySeven = UIAlertAction(title: "5 x 7", style: .default) { [unowned self] action in
self.cropView?.cropAspectRatio = 5.0 / 7.0
}
actionSheet.addAction(fiveBySeven)
let eightByTen = UIAlertAction(title: "8 x 10", style: .default) { [unowned self] action in
self.cropView?.cropAspectRatio = 8.0 / 10.0
}
actionSheet.addAction(eightByTen)
let widescreen = UIAlertAction(title: "16 x 9", style: .default) { [unowned self] action in
let ratio: CGFloat = 9.0 / 16.0
if var cropRect = self.cropView?.cropRect {
let width = cropRect.width
cropRect.size = CGSize(width: width, height: width * ratio)
self.cropView?.cropRect = cropRect
}
}
actionSheet.addAction(widescreen)
let cancel = UIAlertAction(title: "Cancel", style: .default) { [unowned self] action in
self.dismiss(animated: true, completion: nil)
}
actionSheet.addAction(cancel)
if let popoverController = actionSheet.popoverPresentationController {
popoverController.barButtonItem = sender
}
present(actionSheet, animated: true, completion: nil)
}
// MARK: - Private methods
fileprivate func adjustCropRect() {
imageCropRect = CGRect.zero
guard var cropViewCropRect = cropView?.cropRect else {
return
}
cropViewCropRect.origin.x += cropRect.origin.x
cropViewCropRect.origin.y += cropRect.origin.y
let minWidth = min(cropViewCropRect.maxX - cropViewCropRect.minX, cropRect.width)
let minHeight = min(cropViewCropRect.maxY - cropViewCropRect.minY, cropRect.height)
let size = CGSize(width: minWidth, height: minHeight)
cropViewCropRect.size = size
cropView?.cropRect = cropViewCropRect
}
}
//
// EmojiCollectionViewCell.swift
// Photo Editor
//
// Created by Mohamed Hamed on 4/30/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
class EmojiCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var emojiLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14113" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="EmojiCollectionViewCell" id="gTV-IL-0wX" customClass="EmojiCollectionViewCell" customModule="iOSPhotoEditor" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="71" height="69"/>
<autoresizingMask key="autoresizingMask"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
<rect key="frame" x="0.0" y="0.0" width="71" height="69"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="😂" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="HtF-AX-oQb">
<rect key="frame" x="3" y="-1.5" width="65" height="72.5"/>
<viewLayoutGuide key="safeArea" id="T0U-Aa-3Um"/>
<fontDescription key="fontDescription" type="system" pointSize="60"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</view>
<constraints>
<constraint firstItem="HtF-AX-oQb" firstAttribute="centerY" secondItem="gTV-IL-0wX" secondAttribute="centerY" id="aKq-g2-ZSA"/>
<constraint firstItem="HtF-AX-oQb" firstAttribute="centerX" secondItem="gTV-IL-0wX" secondAttribute="centerX" id="eLO-Xr-JQg"/>
</constraints>
<viewLayoutGuide key="safeArea" id="ALQ-3O-CIv"/>
<size key="customSize" width="71" height="69"/>
<connections>
<outlet property="emojiLabel" destination="HtF-AX-oQb" id="Q1y-jj-Bup"/>
</connections>
<point key="canvasLocation" x="44.5" y="90.5"/>
</collectionViewCell>
</objects>
</document>
//
// EmojisCollectionViewDelegate.swift
// Photo Editor
//
// Created by Mohamed Hamed on 4/30/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
class EmojisCollectionViewDelegate: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var stickersViewControllerDelegate : StickersViewControllerDelegate?
let emojiRanges = [
0x1F601...0x1F64F, // emoticons
0x1F30D...0x1F567, // Other additional symbols
0x1F680...0x1F6C0, // Transport and map symbols
0x1F681...0x1F6C5 //Additional transport and map symbols
]
var emojis: [String] = []
override init() {
super.init()
for range in emojiRanges {
for i in range {
let c = String(describing: UnicodeScalar(i)!)
emojis.append(c)
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return emojis.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let emojiLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 90, height: 90))
emojiLabel.textAlignment = .center
emojiLabel.text = emojis[indexPath.item]
emojiLabel.font = UIFont.systemFont(ofSize: 70)
stickersViewControllerDelegate?.didSelectView(view: emojiLabel)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EmojiCollectionViewCell", for: indexPath) as! EmojiCollectionViewCell
cell.emojiLabel.text = emojis[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 4
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
//
// GradientView.swift
// Photo Editor
//
// Created by Mohamed Hamed on 4/11/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
class GradientView: UIView {
@IBInspectable public var gradientFromtop: Bool = true
var gradientLayer = CAGradientLayer()
override func awakeFromNib() {
super.awakeFromNib()
if gradientFromtop == false {
gradientLayer.colors = [UIColor.clear.cgColor, UIColor(white: 0.0, alpha: 0.5).cgColor]
} else {
gradientLayer.colors = [UIColor(white: 0.0, alpha: 0.5).cgColor, UIColor.clear.cgColor]
}
gradientLayer.locations = [NSNumber(value: 0.0 as Float), NSNumber(value: 1.0 as Float)]
backgroundColor = UIColor.clear
layer.addSublayer(gradientLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = bounds
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
</dict>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11134" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11106"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
//
// PhotoEditor+Controls.swift
// Pods
//
// Created by Mohamed Hamed on 6/16/17.
//
//
import Foundation
import UIKit
// MARK: - Control
public enum control: String {
case crop
case sticker
case draw
case text
case save
case share
case clear
public func string() -> String {
return self.rawValue
}
}
extension PhotoEditorViewController {
//MARK: Top Toolbar
@IBAction func cancelButtonTapped(_ sender: Any) {
photoEditorDelegate?.canceledEditing()
self.dismiss(animated: true, completion: nil)
}
@IBAction func cropButtonTapped(_ sender: UIButton) {
let controller = CropViewController()
controller.delegate = self
controller.image = canvasView.toImage()
let navController = UINavigationController(rootViewController: controller)
present(navController, animated: true, completion: nil)
}
@IBAction func stickersButtonTapped(_ sender: Any) {
addStickersViewController()
}
@IBAction func drawButtonTapped(_ sender: Any) {
isDrawing = true
canvasImageView.isUserInteractionEnabled = false
doneButton.isHidden = false
colorPickerView.isHidden = false
hideToolbar(hide: true)
}
@IBAction func textButtonTapped(_ sender: Any) {
isTyping = true
let textView = UITextView(frame: CGRect(x: 0, y: canvasImageView.center.y,
width: UIScreen.main.bounds.width, height: 30))
textView.textAlignment = .center
textView.font = UIFont(name: "Helvetica", size: 30)
textView.textColor = textColor
textView.layer.shadowColor = UIColor.black.cgColor
textView.layer.shadowOffset = CGSize(width: 1.0, height: 0.0)
textView.layer.shadowOpacity = 0.2
textView.layer.shadowRadius = 1.0
textView.layer.backgroundColor = UIColor.clear.cgColor
textView.autocorrectionType = .no
textView.isScrollEnabled = false
textView.delegate = self
self.canvasImageView.addSubview(textView)
addGestures(view: textView)
textView.becomeFirstResponder()
}
@IBAction func doneButtonTapped(_ sender: Any) {
view.endEditing(true)
doneButton.isHidden = true
colorPickerView.isHidden = true
canvasImageView.isUserInteractionEnabled = true
hideToolbar(hide: false)
isDrawing = false
}
//MARK: Bottom Toolbar
@IBAction func saveButtonTapped(_ sender: AnyObject) {
// UIImageWriteToSavedPhotosAlbum(canvasView.toImage(),self, #selector(PhotoEditorViewController.image(_:withPotentialError:contextInfo:)), nil)
print(Util.saveImageToFile(image: canvasView.toImage()) ?? "");
}
@IBAction func shareButtonTapped(_ sender: UIButton) {
let activity = UIActivityViewController(activityItems: [canvasView.toImage()], applicationActivities: nil)
if let popoverController = activity.popoverPresentationController {
popoverController.barButtonItem = UIBarButtonItem(customView: sender)
}
present(activity, animated: true, completion: nil)
}
@IBAction func clearButtonTapped(_ sender: AnyObject) {
//clear drawing
canvasImageView.image = nil
//clear stickers and textviews
for subview in canvasImageView.subviews {
subview.removeFromSuperview()
}
}
@IBAction func continueButtonPressed(_ sender: Any) {
let image = self.canvasView.toImage()
photoEditorDelegate?.doneEditing(image: image)
self.dismiss(animated: true, completion: nil)
}
//MAKR: helper methods
@objc func image(_ image: UIImage, withPotentialError error: NSErrorPointer, contextInfo: UnsafeRawPointer) {
let alert = UIAlertController(title: "Image Saved", message: "Image successfully saved to Photos library", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func hideControls() {
var controls = hiddenControls
for control in controls {
if (control == "clear") {
clearButton.isHidden = true
} else if (control == "crop") {
cropButton.isHidden = true
} else if (control == "draw") {
drawButton.isHidden = true
} else if (control == "save") {
saveButton.isHidden = true
} else if (control == "share") {
shareButton.isHidden = true
} else if (control == "sticker") {
stickerButton.isHidden = true
} else if (control == "text") {
textButton.isHidden = true
}
}
}
}
//
// PhotoEditor+Crop.swift
// Pods
//
// Created by Mohamed Hamed on 6/16/17.
//
//
import Foundation
import UIKit
// MARK: - CropView
extension PhotoEditorViewController: CropViewControllerDelegate {
public func cropViewController(_ controller: CropViewController, didFinishCroppingImage image: UIImage, transform: CGAffineTransform, cropRect: CGRect) {
controller.dismiss(animated: true, completion: nil)
self.setImageView(image: image)
}
public func cropViewControllerDidCancel(_ controller: CropViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
//
// PhotoEditor+Drawing.swift
// Photo Editor
//
// Created by Mohamed Hamed on 6/16/17.
//
//
import UIKit
extension PhotoEditorViewController {
override public func touchesBegan(_ touches: Set<UITouch>,
with event: UIEvent?){
if isDrawing {
swiped = false
if let touch = touches.first {
lastPoint = touch.location(in: self.canvasImageView)
}
}
//Hide stickersVC if clicked outside it
else if stickersVCIsVisible == true {
if let touch = touches.first {
let location = touch.location(in: self.view)
if !stickersViewController.view.frame.contains(location) {
removeStickersView()
}
}
}
}
override public func touchesMoved(_ touches: Set<UITouch>,
with event: UIEvent?){
if isDrawing {
// 6
swiped = true
if let touch = touches.first {
let currentPoint = touch.location(in: canvasImageView)
drawLineFrom(lastPoint, toPoint: currentPoint)
// 7
lastPoint = currentPoint
}
}
}
override public func touchesEnded(_ touches: Set<UITouch>,
with event: UIEvent?){
if isDrawing {
if !swiped {
// draw a single point
drawLineFrom(lastPoint, toPoint: lastPoint)
}
}
}
func drawLineFrom(_ fromPoint: CGPoint, toPoint: CGPoint) {
// 1
let canvasSize = canvasImageView.frame.integral.size
UIGraphicsBeginImageContextWithOptions(canvasSize, false, 0)
if let context = UIGraphicsGetCurrentContext() {
canvasImageView.image?.draw(in: CGRect(x: 0, y: 0, width: canvasSize.width, height: canvasSize.height))
// 2
context.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
context.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))
// 3
context.setLineCap( CGLineCap.round)
context.setLineWidth(5.0)
context.setStrokeColor(drawColor.cgColor)
context.setBlendMode( CGBlendMode.normal)
// 4
context.strokePath()
// 5
canvasImageView.image = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
}
}
//
// PhotoEditor+Font.swift
//
//
// Created by Mohamed Hamed on 6/16/17.
//
//
import Foundation
import UIKit
extension PhotoEditorViewController {
//Resources don't load in main bundle we have to register the font
func registerFont(){
let bundle = Bundle(for: PhotoEditorViewController.self)
let url = bundle.url(forResource: "icomoon", withExtension: "ttf")
guard let fontDataProvider = CGDataProvider(url: url! as CFURL) else {
return
}
let font = CGFont(fontDataProvider)
var error: Unmanaged<CFError>?
guard CTFontManagerRegisterGraphicsFont(font!, &error) else {
return
}
}
}
//
// PhotoEditor+Gestures.swift
// Photo Editor
//
// Created by Mohamed Hamed on 6/16/17.
//
//
import Foundation
import UIKit
extension PhotoEditorViewController : UIGestureRecognizerDelegate {
/**
UIPanGestureRecognizer - Moving Objects
Selecting transparent parts of the imageview won't move the object
*/
@objc func panGesture(_ recognizer: UIPanGestureRecognizer) {
if let view = recognizer.view {
if view is UIImageView {
//Tap only on visible parts on the image
if recognizer.state == .began {
for imageView in subImageViews(view: canvasImageView) {
let location = recognizer.location(in: imageView)
let alpha = imageView.alphaAtPoint(location)
if alpha > 0 {
imageViewToPan = imageView
break
}
}
}
if imageViewToPan != nil {
moveView(view: imageViewToPan!, recognizer: recognizer)
}
} else {
moveView(view: view, recognizer: recognizer)
}
}
}
/**
UIPinchGestureRecognizer - Pinching Objects
If it's a UITextView will make the font bigger so it doen't look pixlated
*/
@objc func pinchGesture(_ recognizer: UIPinchGestureRecognizer) {
if let view = recognizer.view {
if view is UITextView {
let textView = view as! UITextView
if textView.font!.pointSize * recognizer.scale < 90 {
let font = UIFont(name: textView.font!.fontName, size: textView.font!.pointSize * recognizer.scale)
textView.font = font
let sizeToFit = textView.sizeThatFits(CGSize(width: UIScreen.main.bounds.size.width,
height:CGFloat.greatestFiniteMagnitude))
textView.bounds.size = CGSize(width: textView.intrinsicContentSize.width,
height: sizeToFit.height)
} else {
let sizeToFit = textView.sizeThatFits(CGSize(width: UIScreen.main.bounds.size.width,
height:CGFloat.greatestFiniteMagnitude))
textView.bounds.size = CGSize(width: textView.intrinsicContentSize.width,
height: sizeToFit.height)
}
textView.setNeedsDisplay()
} else {
view.transform = view.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
}
recognizer.scale = 1
}
}
/**
UIRotationGestureRecognizer - Rotating Objects
*/
@objc func rotationGesture(_ recognizer: UIRotationGestureRecognizer) {
if let view = recognizer.view {
view.transform = view.transform.rotated(by: recognizer.rotation)
recognizer.rotation = 0
}
}
/**
UITapGestureRecognizer - Taping on Objects
Will make scale scale Effect
Selecting transparent parts of the imageview won't move the object
*/
@objc func tapGesture(_ recognizer: UITapGestureRecognizer) {
if let view = recognizer.view {
if view is UIImageView {
//Tap only on visible parts on the image
for imageView in subImageViews(view: canvasImageView) {
let location = recognizer.location(in: imageView)
let alpha = imageView.alphaAtPoint(location)
if alpha > 0 {
scaleEffect(view: imageView)
break
}
}
} else {
scaleEffect(view: view)
}
}
}
/*
Support Multiple Gesture at the same time
*/
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
@objc func screenEdgeSwiped(_ recognizer: UIScreenEdgePanGestureRecognizer) {
if recognizer.state == .recognized {
if !stickersVCIsVisible {
addStickersViewController()
}
}
}
// to Override Control Center screen edge pan from bottom
override public var prefersStatusBarHidden: Bool {
return true
}
/**
Scale Effect
*/
func scaleEffect(view: UIView) {
view.superview?.bringSubviewToFront(view)
if #available(iOS 10.0, *) {
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
}
let previouTransform = view.transform
UIView.animate(withDuration: 0.2,
animations: {
view.transform = view.transform.scaledBy(x: 1.2, y: 1.2)
},
completion: { _ in
UIView.animate(withDuration: 0.2) {
view.transform = previouTransform
}
})
}
/**
Moving Objects
delete the view if it's inside the delete view
Snap the view back if it's out of the canvas
*/
func moveView(view: UIView, recognizer: UIPanGestureRecognizer) {
hideToolbar(hide: true)
deleteView.isHidden = false
view.superview?.bringSubviewToFront(view)
let pointToSuperView = recognizer.location(in: self.view)
view.center = CGPoint(x: view.center.x + recognizer.translation(in: canvasImageView).x,
y: view.center.y + recognizer.translation(in: canvasImageView).y)
recognizer.setTranslation(CGPoint.zero, in: canvasImageView)
if let previousPoint = lastPanPoint {
//View is going into deleteView
if deleteView.frame.contains(pointToSuperView) && !deleteView.frame.contains(previousPoint) {
if #available(iOS 10.0, *) {
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
}
UIView.animate(withDuration: 0.3, animations: {
view.transform = view.transform.scaledBy(x: 0.25, y: 0.25)
view.center = recognizer.location(in: self.canvasImageView)
})
}
//View is going out of deleteView
else if deleteView.frame.contains(previousPoint) && !deleteView.frame.contains(pointToSuperView) {
//Scale to original Size
UIView.animate(withDuration: 0.3, animations: {
view.transform = view.transform.scaledBy(x: 4, y: 4)
view.center = recognizer.location(in: self.canvasImageView)
})
}
}
lastPanPoint = pointToSuperView
if recognizer.state == .ended {
imageViewToPan = nil
lastPanPoint = nil
hideToolbar(hide: false)
deleteView.isHidden = true
let point = recognizer.location(in: self.view)
if deleteView.frame.contains(point) { // Delete the view
view.removeFromSuperview()
if #available(iOS 10.0, *) {
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.success)
}
} else if !canvasImageView.bounds.contains(view.center) { //Snap the view back to canvasImageView
UIView.animate(withDuration: 0.3, animations: {
view.center = self.canvasImageView.center
})
}
}
}
func subImageViews(view: UIView) -> [UIImageView] {
var imageviews: [UIImageView] = []
for imageView in view.subviews {
if imageView is UIImageView {
imageviews.append(imageView as! UIImageView)
}
}
return imageviews
}
}
//
// PhotoEditor+Keyboard.swift
// Pods
//
// Created by Mohamed Hamed on 6/16/17.
//
//
import Foundation
import UIKit
extension PhotoEditorViewController {
@objc func keyboardDidShow(notification: NSNotification) {
if isTyping {
doneButton.isHidden = false
colorPickerView.isHidden = false
hideToolbar(hide: true)
}
}
@objc func keyboardWillHide(notification: NSNotification) {
isTyping = false
doneButton.isHidden = true
hideToolbar(hide: false)
}
@objc func keyboardWillChangeFrame(_ notification: NSNotification) {
if let userInfo = notification.userInfo {
let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height {
self.colorPickerViewBottomConstraint?.constant = 0.0
} else {
self.colorPickerViewBottomConstraint?.constant = endFrame?.size.height ?? 0.0
}
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
}
//
// PhotoEditor+StickersViewController.swift
// Pods
//
// Created by Mohamed Hamed on 6/16/17.
//
//
import Foundation
import UIKit
extension PhotoEditorViewController {
func addStickersViewController() {
stickersVCIsVisible = true
hideToolbar(hide: true)
self.canvasImageView.isUserInteractionEnabled = false
stickersViewController.stickersViewControllerDelegate = self
for image in self.stickers {
stickersViewController.stickers.append(image)
}
self.addChild(stickersViewController)
self.view.addSubview(stickersViewController.view)
stickersViewController.didMove(toParent: self)
let height = view.frame.height
let width = view.frame.width
stickersViewController.view.frame = CGRect(x: 0, y: self.view.frame.maxY , width: width, height: height)
}
func removeStickersView() {
stickersVCIsVisible = false
self.canvasImageView.isUserInteractionEnabled = true
UIView.animate(withDuration: 0.3,
delay: 0,
options: UIView.AnimationOptions.curveEaseIn,
animations: { () -> Void in
var frame = self.stickersViewController.view.frame
frame.origin.y = UIScreen.main.bounds.maxY
self.stickersViewController.view.frame = frame
}, completion: { (finished) -> Void in
self.stickersViewController.view.removeFromSuperview()
self.stickersViewController.removeFromParent()
self.hideToolbar(hide: false)
})
}
}
extension PhotoEditorViewController: StickersViewControllerDelegate {
func didSelectView(view: UIView) {
self.removeStickersView()
view.center = canvasImageView.center
self.canvasImageView.addSubview(view)
//Gestures
addGestures(view: view)
}
func didSelectImage(image: UIImage) {
self.removeStickersView()
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
imageView.frame.size = CGSize(width: 150, height: 150)
imageView.center = canvasImageView.center
self.canvasImageView.addSubview(imageView)
//Gestures
addGestures(view: imageView)
}
func stickersViewDidDisappear() {
stickersVCIsVisible = false
hideToolbar(hide: false)
}
func addGestures(view: UIView) {
//Gestures
view.isUserInteractionEnabled = true
let panGesture = UIPanGestureRecognizer(target: self,
action: #selector(PhotoEditorViewController.panGesture))
panGesture.minimumNumberOfTouches = 1
panGesture.maximumNumberOfTouches = 1
panGesture.delegate = self
view.addGestureRecognizer(panGesture)
let pinchGesture = UIPinchGestureRecognizer(target: self,
action: #selector(PhotoEditorViewController.pinchGesture))
pinchGesture.delegate = self
view.addGestureRecognizer(pinchGesture)
let rotationGestureRecognizer = UIRotationGestureRecognizer(target: self,
action:#selector(PhotoEditorViewController.rotationGesture) )
rotationGestureRecognizer.delegate = self
view.addGestureRecognizer(rotationGestureRecognizer)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(PhotoEditorViewController.tapGesture))
view.addGestureRecognizer(tapGesture)
}
}
//
// PhotoEditor+UITextView.swift
// Pods
//
// Created by Mohamed Hamed on 6/16/17.
//
//
import Foundation
import UIKit
extension PhotoEditorViewController: UITextViewDelegate {
public func textViewDidChange(_ textView: UITextView) {
let rotation = atan2(textView.transform.b, textView.transform.a)
if rotation == 0 {
let oldFrame = textView.frame
let sizeToFit = textView.sizeThatFits(CGSize(width: oldFrame.width, height:CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: oldFrame.width, height: sizeToFit.height)
}
}
public func textViewDidBeginEditing(_ textView: UITextView) {
isTyping = true
lastTextViewTransform = textView.transform
lastTextViewTransCenter = textView.center
lastTextViewFont = textView.font!
activeTextView = textView
textView.superview?.bringSubviewToFront(textView)
textView.font = UIFont(name: "Helvetica", size: 30)
UIView.animate(withDuration: 0.3,
animations: {
textView.transform = CGAffineTransform.identity
textView.center = CGPoint(x: UIScreen.main.bounds.width / 2,
y: UIScreen.main.bounds.height / 5)
}, completion: nil)
}
public func textViewDidEndEditing(_ textView: UITextView) {
guard lastTextViewTransform != nil && lastTextViewTransCenter != nil && lastTextViewFont != nil
else {
return
}
activeTextView = nil
textView.font = self.lastTextViewFont!
UIView.animate(withDuration: 0.3,
animations: {
textView.transform = self.lastTextViewTransform!
textView.center = self.lastTextViewTransCenter!
}, completion: nil)
}
}
//
// ViewController.swift
// Photo Editor
//
// Created by Mohamed Hamed on 4/23/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
import Kingfisher
public final class PhotoEditorViewController: UIViewController {
/** holding the 2 imageViews original image and drawing & stickers */
@IBOutlet weak var canvasView: UIView!
//To hold the image
@IBOutlet var imageView: UIImageView!
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
//To hold the drawings and stickers
@IBOutlet weak var canvasImageView: UIImageView!
@IBOutlet weak var topToolbar: UIView!
@IBOutlet weak var bottomToolbar: UIView!
@IBOutlet weak var topGradient: UIView!
@IBOutlet weak var bottomGradient: UIView!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var deleteView: UIView!
@IBOutlet weak var colorsCollectionView: UICollectionView!
@IBOutlet weak var colorPickerView: UIView!
@IBOutlet weak var colorPickerViewBottomConstraint: NSLayoutConstraint!
//Controls
@IBOutlet weak var cropButton: UIButton!
@IBOutlet weak var stickerButton: UIButton!
@IBOutlet weak var drawButton: UIButton!
@IBOutlet weak var textButton: UIButton!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var clearButton: UIButton!
@objc public var imgPath: String?
/**
Array of Stickers -UIImage- that the user will choose from
*/
@objc public var stickers : [UIImage] = []
/**
Array of Colors that will show while drawing or typing
*/
@objc public var colors : [UIColor] = []
@objc public var photoEditorDelegate: PhotoEditorDelegate?
var colorsCollectionViewDelegate: ColorsCollectionViewDelegate!
// list of controls to be hidden
@objc public var hiddenControls : [NSString] = []
var stickersVCIsVisible = false
var drawColor: UIColor = UIColor.black
var textColor: UIColor = UIColor.white
var isDrawing: Bool = false
var lastPoint: CGPoint!
var swiped = false
var lastPanPoint: CGPoint?
var lastTextViewTransform: CGAffineTransform?
var lastTextViewTransCenter: CGPoint?
var lastTextViewFont:UIFont?
var activeTextView: UITextView?
var imageViewToPan: UIImageView?
var isTyping: Bool = false
var stickersViewController: StickersViewController!
//Register Custom font before we load XIB
public override func loadView() {
registerFont()
super.loadView()
}
override public func viewDidLoad() {
super.viewDidLoad()
self.loadImageForPath(path: self.imgPath ?? "");
deleteView.layer.cornerRadius = deleteView.bounds.height / 2
deleteView.layer.borderWidth = 2.0
deleteView.layer.borderColor = UIColor.white.cgColor
deleteView.clipsToBounds = true
let edgePan = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(screenEdgeSwiped))
edgePan.edges = .bottom
edgePan.delegate = self
self.view.addGestureRecognizer(edgePan)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow),
name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self,selector: #selector(keyboardWillChangeFrame(_:)),
name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
configureCollectionView()
stickersViewController = StickersViewController(nibName: "StickersViewController", bundle: Bundle(for: StickersViewController.self))
hideControls()
}
func configureCollectionView() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 30, height: 30)
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
colorsCollectionView.collectionViewLayout = layout
colorsCollectionViewDelegate = ColorsCollectionViewDelegate()
colorsCollectionViewDelegate.colorDelegate = self
if !colors.isEmpty {
colorsCollectionViewDelegate.colors = colors
}
colorsCollectionView.delegate = colorsCollectionViewDelegate
colorsCollectionView.dataSource = colorsCollectionViewDelegate
colorsCollectionView.register(
UINib(nibName: "ColorCollectionViewCell", bundle: Bundle(for: ColorCollectionViewCell.self)),
forCellWithReuseIdentifier: "ColorCollectionViewCell")
}
func loadImageForPath(path: String) {
if let imgUrl = URL(string: path) {
self.imageView.kf.setImage(with: imgUrl, placeholder: nil, options: nil, progressBlock: nil) { (result) in
switch result {
case .success(let success):
print(success.image, success.originalSource)
self.setImageView(image: success.image)
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
func setImageView(image: UIImage) {
imageView.image = image
let size = image.suitableSize(widthLimit: UIScreen.main.bounds.width)
imageViewHeightConstraint.constant = (size?.height)!
}
func hideToolbar(hide: Bool) {
topToolbar.isHidden = hide
topGradient.isHidden = hide
bottomToolbar.isHidden = hide
bottomGradient.isHidden = hide
}
}
extension PhotoEditorViewController: ColorDelegate {
func didSelectColor(color: UIColor) {
if isDrawing {
self.drawColor = color
} else if activeTextView != nil {
activeTextView?.textColor = color
textColor = color
}
}
}
This diff is collapsed.
//
// Protocols.swift
// Photo Editor
//
// Created by Mohamed Hamed on 6/15/17.
//
//
import Foundation
import UIKit
/**
- didSelectView
- didSelectImage
- stickersViewDidDisappear
*/
@objc public protocol PhotoEditorDelegate {
/**
- Parameter image: edited Image
*/
func doneEditing(image: UIImage)
/**
StickersViewController did Disappear
*/
func canceledEditing()
}
/**
- didSelectView
- didSelectImage
- stickersViewDidDisappear
*/
protocol StickersViewControllerDelegate {
/**
- Parameter view: selected view from StickersViewController
*/
func didSelectView(view: UIView)
/**
- Parameter image: selected Image from StickersViewController
*/
func didSelectImage(image: UIImage)
/**
StickersViewController did Disappear
*/
func stickersViewDidDisappear()
}
/**
- didSelectColor
*/
protocol ColorDelegate {
func didSelectColor(color: UIColor)
}
//
// ResizeControl.swift
// CropViewController
//
// Created by Guilherme Moura on 2/26/16.
// Copyright © 2016 Reefactor, Inc. All rights reserved.
// Credit https://github.com/sprint84/PhotoCropEditor
import UIKit
protocol ResizeControlDelegate: class {
func resizeControlDidBeginResizing(_ control: ResizeControl)
func resizeControlDidResize(_ control: ResizeControl)
func resizeControlDidEndResizing(_ control: ResizeControl)
}
class ResizeControl: UIView {
weak var delegate: ResizeControlDelegate?
var translation = CGPoint.zero
var enabled = true
fileprivate var startPoint = CGPoint.zero
override init(frame: CGRect) {
super.init(frame: CGRect(x: frame.origin.x, y: frame.origin.y, width: 44.0, height: 44.0))
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(frame: CGRect(x: 0, y: 0, width: 44.0, height: 44.0))
initialize()
}
fileprivate func initialize() {
backgroundColor = UIColor.clear
isExclusiveTouch = true
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ResizeControl.handlePan(_:)))
addGestureRecognizer(gestureRecognizer)
}
@objc func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
if !enabled {
return
}
switch gestureRecognizer.state {
case .began:
let translation = gestureRecognizer.translation(in: superview)
startPoint = CGPoint(x: round(translation.x), y: round(translation.y))
delegate?.resizeControlDidBeginResizing(self)
case .changed:
let translation = gestureRecognizer.translation(in: superview)
self.translation = CGPoint(x: round(startPoint.x + translation.x), y: round(startPoint.y + translation.y))
delegate?.resizeControlDidResize(self)
case .ended, .cancelled:
delegate?.resizeControlDidEndResizing(self)
default: ()
}
}
}
//
// SceneDelegate.swift
// GeekImageEditor
//
// Created by wenjindu on 2020/2/20.
// Copyright © 2020 wenjindu. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
//
// StickerCollectionViewCell.swift
// Photo Editor
//
// Created by Mohamed Hamed on 4/23/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
class StickerCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var stickerImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
}
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14113" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="StickerCollectionViewCell" id="gTV-IL-0wX" customClass="StickerCollectionViewCell" customModule="iOSPhotoEditor" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="139" height="81"/>
<autoresizingMask key="autoresizingMask"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
<rect key="frame" x="0.0" y="0.0" width="139" height="81"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<imageView userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="KOC-sF-DQ7">
<rect key="frame" x="0.0" y="0.0" width="139" height="81"/>
</imageView>
</subviews>
</view>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="KOC-sF-DQ7" firstAttribute="leading" secondItem="gTV-IL-0wX" secondAttribute="leading" id="2yY-EC-OBG"/>
<constraint firstAttribute="trailing" secondItem="KOC-sF-DQ7" secondAttribute="trailing" id="IjG-hv-eoa"/>
<constraint firstAttribute="bottom" secondItem="KOC-sF-DQ7" secondAttribute="bottom" id="LSw-wL-WBM"/>
<constraint firstItem="KOC-sF-DQ7" firstAttribute="top" secondItem="gTV-IL-0wX" secondAttribute="top" id="Zq3-3X-uWQ"/>
</constraints>
<viewLayoutGuide key="safeArea" id="QQg-2I-3Mc"/>
<size key="customSize" width="139" height="81"/>
<connections>
<outlet property="stickerImage" destination="KOC-sF-DQ7" id="qYt-m0-cB8"/>
</connections>
<point key="canvasLocation" x="78.5" y="76.5"/>
</collectionViewCell>
</objects>
</document>
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14113" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="StickersViewController" customModule="iOSPhotoEditor" customModuleProvider="target">
<connections>
<outlet property="headerView" destination="Jqb-lC-sL5" id="2Bt-iO-hyv"/>
<outlet property="holdView" destination="caC-0e-fET" id="T8J-gB-ag8"/>
<outlet property="pageControl" destination="fPm-Rj-wEI" id="wow-uc-U80"/>
<outlet property="scrollView" destination="389-Pb-g4p" id="EiN-Xe-ZxU"/>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Jqb-lC-sL5">
<rect key="frame" x="0.0" y="0.0" width="375" height="40"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="caC-0e-fET">
<rect key="frame" x="162.5" y="8" width="50" height="5"/>
<color key="backgroundColor" red="0.96470588239999999" green="0.96470588239999999" blue="0.96470588239999999" alpha="1" colorSpace="calibratedRGB"/>
<constraints>
<constraint firstAttribute="width" constant="50" id="GqZ-hh-S9K"/>
<constraint firstAttribute="height" constant="5" id="uq0-60-mnE"/>
</constraints>
</view>
<pageControl opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" numberOfPages="3" translatesAutoresizingMaskIntoConstraints="NO" id="fPm-Rj-wEI">
<rect key="frame" x="168" y="13" width="39" height="37"/>
</pageControl>
</subviews>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="caC-0e-fET" firstAttribute="top" secondItem="Jqb-lC-sL5" secondAttribute="top" constant="8" id="S62-GD-S5G"/>
<constraint firstAttribute="height" constant="40" id="Tl2-jg-Adq"/>
<constraint firstItem="fPm-Rj-wEI" firstAttribute="centerX" secondItem="Jqb-lC-sL5" secondAttribute="centerX" id="jKc-Hd-3e8"/>
<constraint firstItem="fPm-Rj-wEI" firstAttribute="top" secondItem="caC-0e-fET" secondAttribute="bottom" id="oH1-Ez-1Ze"/>
<constraint firstItem="caC-0e-fET" firstAttribute="centerX" secondItem="Jqb-lC-sL5" secondAttribute="centerX" id="qvF-zt-xDj"/>
</constraints>
</view>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" directionalLockEnabled="YES" translatesAutoresizingMaskIntoConstraints="NO" id="389-Pb-g4p">
<rect key="frame" x="0.0" y="40" width="375" height="627"/>
</scrollView>
</subviews>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="Jqb-lC-sL5" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" id="534-wp-qUu"/>
<constraint firstAttribute="bottom" secondItem="389-Pb-g4p" secondAttribute="bottom" id="alT-c1-6ub"/>
<constraint firstItem="389-Pb-g4p" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="eu1-LX-lYG"/>
<constraint firstItem="Jqb-lC-sL5" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="fvh-Gm-lz3"/>
<constraint firstAttribute="trailing" secondItem="389-Pb-g4p" secondAttribute="trailing" id="gLR-A6-iQ1"/>
<constraint firstItem="389-Pb-g4p" firstAttribute="top" secondItem="Jqb-lC-sL5" secondAttribute="bottom" id="iQj-xf-VZX"/>
<constraint firstAttribute="trailing" secondItem="Jqb-lC-sL5" secondAttribute="trailing" id="tYL-lr-Vzj"/>
</constraints>
<nil key="simulatedStatusBarMetrics"/>
<viewLayoutGuide key="safeArea" id="FYC-GN-PYj"/>
<point key="canvasLocation" x="33.5" y="54.5"/>
</view>
</objects>
</document>
//
// UIImage+Crop.swift
// CropViewController
//
// Created by Guilherme Moura on 2/26/16.
// Copyright © 2016 Reefactor, Inc. All rights reserved.
// Credit https://github.com/sprint84/PhotoCropEditor
import UIKit
extension UIImage {
func rotatedImageWithTransform(_ rotation: CGAffineTransform, croppedToRect rect: CGRect) -> UIImage {
let rotatedImage = rotatedImageWithTransform(rotation)
let scale = rotatedImage.scale
let cropRect = rect.applying(CGAffineTransform(scaleX: scale, y: scale))
let croppedImage = rotatedImage.cgImage?.cropping(to: cropRect)
let image = UIImage(cgImage: croppedImage!, scale: self.scale, orientation: rotatedImage.imageOrientation)
return image
}
fileprivate func rotatedImageWithTransform(_ transform: CGAffineTransform) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, true, scale)
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: size.width / 2.0, y: size.height / 2.0)
context?.concatenate(transform)
context?.translateBy(x: size.width / -2.0, y: size.height / -2.0)
draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return rotatedImage!
}
}
//
// UIImage+Size.swift
// Photo Editor
//
// Created by Mohamed Hamed on 5/2/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
public extension UIImage {
/**
Suitable size for specific height or width to keep same image ratio
*/
func suitableSize(heightLimit: CGFloat? = nil,
widthLimit: CGFloat? = nil )-> CGSize? {
if let height = heightLimit {
let width = (height / self.size.height) * self.size.width
return CGSize(width: width, height: height)
}
if let width = widthLimit {
let height = (width / self.size.width) * self.size.height
return CGSize(width: width, height: height)
}
return nil
}
}
//
// UIImageViewExtenstions.swift
// Photo Editor
//
// Created by Mohamed Hamed on 5/10/17.
//
//
import Foundation
import UIKit
extension UIImageView {
func alphaAtPoint(_ point: CGPoint) -> CGFloat {
var pixel: [UInt8] = [0, 0, 0, 0]
let colorSpace = CGColorSpaceCreateDeviceRGB();
let alphaInfo = CGImageAlphaInfo.premultipliedLast.rawValue
guard let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: alphaInfo) else {
return 0
}
context.translateBy(x: -point.x, y: -point.y);
layer.render(in: context)
let floatAlpha = CGFloat(pixel[3])
return floatAlpha
}
}
//
// UIView+Image.swift
// Photo Editor
//
// Created by Mohamed Hamed on 4/23/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
extension UIView {
/**
Convert UIView to UIImage
*/
func toImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
self.drawHierarchy(in: self.bounds, afterScreenUpdates: false)
let snapshotImageFromMyView = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return snapshotImageFromMyView!
}
}
//
// Util.swift
// GeekImageEditor
//
// Created by wenjindu on 2020/2/20.
// Copyright © 2020 wenjindu. All rights reserved.
//
import UIKit
class Util: NSObject {
static public func saveImageToFile(image: UIImage?) -> String? {
var imgPath: String? = nil
if image != nil {
let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
let imageName = String.init(format: "%.f", Date().timeIntervalSince1970 * 1000);
if let imgData = image!.pngData() {
imgPath = "\(path)/\(imageName).png";
let url = URL(string: "file://\(imgPath ?? "")")!;
try? imgData.write(to: url, options: .atomic)
} else {
if let imgData = image!.jpegData(compressionQuality: 1.0) {
imgPath = "\(path)/\(imageName).jpg";
let url = URL(string: "file://\(imgPath ?? "")")!;
try? imgData.write(to: url, options: .atomic)
}
}
}
return imgPath
}
}
//
// ViewController.swift
// GeekImageEditor
//
// Created by wenjindu on 2020/2/20.
// Copyright © 2020 wenjindu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func tapBtnAction(_ sender: Any) {
let photo = PhotoEditorViewController.init(nibName: "PhotoEditorViewController", bundle: nil)
photo.imgPath = "http://a4.att.hudong.com/44/71/01300001009299133077717708025.jpg"
photo.modalPresentationStyle = .fullScreen
present(photo, animated: true, completion: nil)
}
}
//
// GeekImageEditorTests.swift
// GeekImageEditorTests
//
// Created by wenjindu on 2020/2/20.
// Copyright © 2020 wenjindu. All rights reserved.
//
import XCTest
@testable import GeekImageEditor
class GeekImageEditorTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
//
// GeekImageEditorUITests.swift
// GeekImageEditorUITests
//
// Created by wenjindu on 2020/2/20.
// Copyright © 2020 wenjindu. All rights reserved.
//
import XCTest
class GeekImageEditorUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
platform :ios, '10'
target 'GeekImageEditor' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for editorTest
pod 'Kingfisher'
end
PODS:
- Kingfisher (5.13.1):
- Kingfisher/Core (= 5.13.1)
- Kingfisher/Core (5.13.1)
DEPENDENCIES:
- Kingfisher
SPEC REPOS:
https://github.com/cocoapods/specs.git:
- Kingfisher
SPEC CHECKSUMS:
Kingfisher: f33a848445e33c543620812158dc5d47f6bf90df
PODFILE CHECKSUM: b5fe8a425532c409b30833dbcf09dfc2fa4ea36a
COCOAPODS: 1.7.0
The MIT License (MIT)
Copyright (c) 2019 Wei Wang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This diff is collapsed.
//
// CacheSerializer.swift
// Kingfisher
//
// Created by Wei Wang on 2016/09/02.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
/// An `CacheSerializer` is used to convert some data to an image object after
/// retrieving it from disk storage, and vice versa, to convert an image to data object
/// for storing to the disk storage.
public protocol CacheSerializer {
/// Gets the serialized data from a provided image
/// and optional original data for caching to disk.
///
/// - Parameters:
/// - image: The image needed to be serialized.
/// - original: The original data which is just downloaded.
/// If the image is retrieved from cache instead of
/// downloaded, it will be `nil`.
/// - Returns: The data object for storing to disk, or `nil` when no valid
/// data could be serialized.
func data(with image: KFCrossPlatformImage, original: Data?) -> Data?
/// Gets an image from provided serialized data.
///
/// - Parameters:
/// - data: The data from which an image should be deserialized.
/// - options: The parsed options for deserialization.
/// - Returns: An image deserialized or `nil` when no valid image
/// could be deserialized.
func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?
/// Gets an image deserialized from provided data.
///
/// - Parameters:
/// - data: The data from which an image should be deserialized.
/// - options: Options for deserialization.
/// - Returns: An image deserialized or `nil` when no valid image
/// could be deserialized.
/// - Note:
/// This method is deprecated. Please implement the version with
/// `KingfisherParsedOptionsInfo` as parameter instead.
@available(*, deprecated,
message: "Deprecated. Implement the method with same name but with `KingfisherParsedOptionsInfo` instead.")
func image(with data: Data, options: KingfisherOptionsInfo?) -> KFCrossPlatformImage?
}
extension CacheSerializer {
public func image(with data: Data, options: KingfisherOptionsInfo?) -> KFCrossPlatformImage? {
return image(with: data, options: KingfisherParsedOptionsInfo(options))
}
}
/// Represents a basic and default `CacheSerializer` used in Kingfisher disk cache system.
/// It could serialize and deserialize images in PNG, JPEG and GIF format. For
/// image other than these formats, a normalized `pngRepresentation` will be used.
public struct DefaultCacheSerializer: CacheSerializer {
/// The default general cache serializer used across Kingfisher's cache.
public static let `default` = DefaultCacheSerializer()
/// The compression quality when converting image to a lossy format data. Default is 1.0.
public var compressionQuality: CGFloat = 1.0
/// Whether the original data should be preferred when serializing the image.
/// If `true`, the input original data will be checked first and used unless the data is `nil`.
/// In that case, the serialization will fall back to creating data from image.
public var preferCacheOriginalData: Bool = false
/// Creates a cache serializer that serialize and deserialize images in PNG, JPEG and GIF format.
///
/// - Note:
/// Use `DefaultCacheSerializer.default` unless you need to specify your own properties.
///
public init() { }
/// - Parameters:
/// - image: The image needed to be serialized.
/// - original: The original data which is just downloaded.
/// If the image is retrieved from cache instead of
/// downloaded, it will be `nil`.
/// - Returns: The data object for storing to disk, or `nil` when no valid
/// data could be serialized.
///
/// - Note:
/// Only when `original` contains valid PNG, JPEG and GIF format data, the `image` will be
/// converted to the corresponding data type. Otherwise, if the `original` is provided but it is not
/// If `original` is `nil`, the input `image` will be encoded as PNG data.
public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? {
if preferCacheOriginalData {
return original ??
image.kf.data(
format: original?.kf.imageFormat ?? .unknown,
compressionQuality: compressionQuality
)
} else {
return image.kf.data(
format: original?.kf.imageFormat ?? .unknown,
compressionQuality: compressionQuality
)
}
}
/// Gets an image deserialized from provided data.
///
/// - Parameters:
/// - data: The data from which an image should be deserialized.
/// - options: Options for deserialization.
/// - Returns: An image deserialized or `nil` when no valid image
/// could be deserialized.
public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment