如何从UIImageView获取显示的图像帧?
问题描述:
我修改了UIImageView的contentMode属性.所以我的图像的框架不等于UIImageView的框架.我的问题是如何从UIImageView检索图像的框架.
I modify the UIImageView's contentMode property. So my image's frame is not equal to the frame of UIImageView. My problem is how to retrive the image's frame from UIImageView.
如以下示例所示,橙色矩形是UIImageView的边框.显然,图像的帧与UIImageView不同.
As the following example, the orange rectangle is the UIImageView's border. It is obviously that the frame of image is not the same as UIImageView.
答
如果是UIViewContentModeScaleAspectFit
,则类似于以下内容:
If it's UIViewContentModeScaleAspectFit
, it's something like this:
UIImageView *iv; // your image view
CGSize imageSize = iv.image.size;
CGFloat imageScale = fminf(CGRectGetWidth(iv.bounds)/imageSize.width, CGRectGetHeight(iv.bounds)/imageSize.height);
CGSize scaledImageSize = CGSizeMake(imageSize.width*imageScale, imageSize.height*imageScale);
CGRect imageFrame = CGRectMake(roundf(0.5f*(CGRectGetWidth(iv.bounds)-scaledImageSize.width)), roundf(0.5f*(CGRectGetHeight(iv.bounds)-scaledImageSize.height)), roundf(scaledImageSize.width), roundf(scaledImageSize.height));