Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active October 25, 2017 03:13
Show Gist options
  • Select an option

  • Save ha1f/2c436e97b119afb7dd923da8687318ef to your computer and use it in GitHub Desktop.

Select an option

Save ha1f/2c436e97b119afb7dd923da8687318ef to your computer and use it in GitHub Desktop.
/// 中心に画像を描画する
class RotatableImageView: UIView {
var image: UIImage? {
didSet {
setNeedsDisplay()
}
}
var angle: CGFloat = 0.0
var scale: CGFloat = 1.0
var translateX: CGFloat = 0.0
var translateY: CGFloat = 0.0
var contentSize: CGSize {
return image?.size ?? .zero
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
_commonInit()
}
private func _commonInit() {
self.backgroundColor = .clear
}
override func sizeToFit() {
self.frame = CGRect(origin: self.frame.origin, size: contentSize)
}
func getImage(of frame: CGRect) -> UIImage? {
UIGraphicsBeginImageContext(bounds.size)
defer {
UIGraphicsEndImageContext()
}
guard let context = _draw() else {
return nil
}
return context.makeImage()?.cropping(to: frame).map { UIImage(cgImage: $0) }
}
@discardableResult
private func _draw() -> CGContext? {
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
guard let image = image else {
return context
}
// clear
context.clear(bounds)
// background
context.setFillColor((backgroundColor ?? UIColor.clear).cgColor)
context.fill(bounds)
// 座標系を一時退避
context.saveGState()
// 座標系を中心に
context.translateBy(x: bounds.midX + translateX, y: bounds.midY + translateY)
let imageFrame = CGRect(origin: .zero, size: image.size)
// rotate
context.rotate(by: angle)
// scale
context.scaleBy(x: scale, y: scale)
// draw
image.draw(in: imageFrame.offsetBy(dx: -imageFrame.midX, dy: -imageFrame.midY))
// 座標系を戻す
context.restoreGState()
return context
}
override func draw(_ rect: CGRect) {
_draw()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment