-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUIImage+Extensions.swift
67 lines (50 loc) · 2.34 KB
/
UIImage+Extensions.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
60
61
62
63
64
65
66
67
//
// UIImage+Extensions.swift
// Swift Utilities
//
// Created by Tre`Von McKay on 11/4/16.
//
import Foundation
import UIKit
extension UIImage{
static func scaleImage(_ image:UIImage, width:CGFloat, height:CGFloat) -> UIImage{
let scaleSize = CGSize(width: width, height: height)
UIGraphicsBeginImageContextWithOptions(scaleSize, false, 0.0)
image.draw(in: CGRect(x: 0, y: 0, width: scaleSize.height, height: scaleSize.width))
let scaledImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return scaledImage
}
func scaledTo(_ targetSize: CGSize) -> UIImage {
let size = self.size
let widthRatio = targetSize.width / self.size.width
let heightRatio = targetSize.height / self.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func scaled(byHeight maxHeight:CGFloat) -> UIImage {
let originalWidth = self.size.width
let originalHeight = self.size.height
let newWidth = (originalWidth * maxHeight) / originalHeight
return self.scaledTo(CGSize(width: newWidth, height: maxHeight))
}
func scaled(byWidth maxWidth:CGFloat) -> UIImage {
let originalWidth = self.size.width
let originalHeight = self.size.height
let newHeight = (originalHeight * maxWidth) / originalWidth
return self.scaledTo(CGSize(width: maxWidth, height: newHeight))
}
}