if you want to calculate it yourself, use below code written by me.
func getImageFrameInImageView(imageView : UIImageView) -> CGRect {
/*
by 徐明刚, [email protected]
算法:
设高宽比 r = h/w, 则:r(imageView) 缩写成r(v), r(image)缩写为r(i),
if r(i) > r(v), 则
h(i) = h(v),
h(i) / w(i) = r(i) -> w(i) = h(i) / r(i)
y = 0
x = (w(v) / 2) - (w(i) / 2)
反之
*/
let image = imageView.image!
let wi = image.size.width
let hi = image.size.height
print("wi:\(wi), hi:\(hi)")
let wv = imageView.frame.width
let hv = imageView.frame.height
print("wv:\(wv), hv:\(hv)")
let ri = hi / wi
let rv = hv / wv
print("ri:\(ri), rv:\(rv)")
var x, y, w, h: CGFloat
if ri > rv {
h = hv
w = h / ri
x = (wv / 2) - (w / 2)
y = 0
} else {
w = wv
h = w * ri
x = 0
y = (hv / 2) - (h / 2)
}
return CGRect(x: x, y: y, width: w, height: h)
}
To test if the function is right or not, I've used another view identifying the border of the image in UIImageView.
let frameIdentifyBorderView = UIView(frame: imageFrameInImageView)
frameIdentifyBorderView.layer.borderWidth = 3
frameIdentifyBorderView.layer.borderColor = UIColor.blueColor().CGColor
imageView.addSubview(frameIdentifyBorderView)
perfect!