Created
August 2, 2015 19:16
-
-
Save Ridwy/c03b7a35fee8a8d438dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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