Skip to content

Instantly share code, notes, and snippets.

@Ridwy
Created August 2, 2015 19:16
Show Gist options
  • Save Ridwy/c03b7a35fee8a8d438dc to your computer and use it in GitHub Desktop.
Save Ridwy/c03b7a35fee8a8d438dc to your computer and use it in GitHub Desktop.
//
// CNImageView.swift
// ImageView
//
// Created by Chiharu Nameki on 2015/08/02.
// Copyright (c) 2015 Chiharu Nameki. All rights reserved.
//
import UIKit
class CNImageView: UIImageView {
var imageCenter: CGPoint = CGPointMake(0.5, 0.5) {
didSet {
updateContentsRect()
}
}
override var image: UIImage? {
didSet {
updateContentsRect()
}
}
override func layoutSubviews() {
super.layoutSubviews()
updateContentsRect()
}
private func updateContentsRect() {
if let image = image {
let scale = max(bounds.width / image.size.width, bounds.height / image.size.height)
let w = min(1.0, bounds.width / (scale * image.size.width))
let h = min(1.0, bounds.height / (scale * image.size.height))
let x = imageCenter.x * (1.0 - w)
let y = imageCenter.y * (1.0 - h)
layer.contentsRect = CGRectMake(x, y, w, h)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment