Skip to content

Instantly share code, notes, and snippets.

@woodycatliu
Last active January 28, 2022 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woodycatliu/1a285009337c032a477a9bbb340d05ea to your computer and use it in GitHub Desktop.
Save woodycatliu/1a285009337c032a477a9bbb340d05ea to your computer and use it in GitHub Desktop.
Optimize the UIImageView

After reading "High Performance iOS Apps" Chapter7. UIImageView, and lookiing for some information in google.
Image Resizing Techniques I try to enhancements with resize image related code in a custom UIImageView (AutoDownsampingImageView).

See the orign code OptimizationImageView.swift

// just use   
let imageView: AutoDownsampingImageView = AutoDownsampingImageView()   
imageView.image = image
// DownsampingImageView
//
// Created by Woody on 2022/1/28.
//
import UIKit
fileprivate var WidthScale: (_ r: CGFloat, _ l: CGFloat)-> CGFloat = {
return Scale($0, $1)
}
fileprivate var HeightScale: (_ r: CGFloat, _ l: CGFloat)-> CGFloat = {
return Scale($0, $1)
}
fileprivate var Scale: (_ r: CGFloat, _ l: CGFloat)-> CGFloat = {
return $0 / $1
}
extension UIImage {
func resizeImageIfNeed(for size: CGSize)-> UIImage {
guard needResizeimage(for: size) else { return self }
return resizeImage(for: size)
}
func needResizeimage(for size: CGSize)-> Bool {
let orign: CGSize = self.size
return WidthScale(orign.width, size.width) >= 0.5 || HeightScale(orign.height, size.height) >= 0.5
}
func resizeImage(for size: CGSize)-> UIImage {
#if DEBUG
print("\(#function) is Action")
#endif
let render = UIGraphicsImageRenderer(size: size)
return render.image { ctx in self.draw(in: .init(origin: .zero, size: size))}
}
}
extension UIImageView {
func resizeImageIfNeed() {
self.image = image?.resizeImage(for: bounds.size)
}
}
class AutoDownsampingImageView: UIImageView {
override var bounds: CGRect {
didSet {
resizeImageIfNeed()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment