-
Notifications
You must be signed in to change notification settings - Fork 0
/
SquareImage.swift
59 lines (51 loc) · 1.7 KB
/
SquareImage.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// SquareImage.swift
// Check
//
// Created by Puspank Kumar on 22/08/20.
// Copyright © 2020 Puspank Kumar. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
var squared: UIImage? {
let originalWidth = size.width
let originalHeight = size.height
var x: CGFloat = 0.0
var y: CGFloat = 0.0
var edge: CGFloat = 0.0
if (originalWidth > originalHeight) {
// landscape
edge = originalHeight
x = (originalWidth - edge) / 2.0
y = 0.0
} else if (originalHeight > originalWidth) {
// portrait
edge = originalWidth
x = 0.0
y = (originalHeight - originalWidth) / 2.0
} else {
// square
edge = originalWidth
}
let cropSquare = CGRect(x: x, y: y, width: edge, height: edge)
guard let imageRef = cgImage?.cropping(to: cropSquare) else { return nil }
return UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)
}
func resized(maxSize: CGFloat) -> UIImage? {
let scale: CGFloat
if size.width > size.height {
scale = maxSize / size.width
}
else {
scale = maxSize / size.height
}
let newWidth = size.width * scale
let newHeight = size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}