iOS图片AVMakeRectWithAspectRatioInsideRect妙用

来源:互联网 发布:低头族数据统计 编辑:程序博客网 时间:2024/06/06 03:02

from:http://www.jianshu.com/p/827090aa933b?utm_campaign=maleskine&utm_content=note&utm_medium=writer_share&utm_source=weibo

在 iOS 中我们经常会碰到一些 imagView 的 UIContentMode的显示方式,最初我怎么记也搞不太清楚,后来我看到了这幅图,我发现我遇到了指明灯了,一图解千惑,这里分享给大家。(ps:大家别说我菜啊)

image
image

1.神器计算图片位置的函数:AVMakeRectWithAspectRatioInsideRect()

是根据image的比例进行居中显示, 如果没用这个函数, 要自己计算一下, 之前也做过这方面的需求, 我是调整imageView的frame来解决的, 粘上代码:

<span style="font-size:14px;">    if(imgWidth/imgHeight < screenWidth/screenHeight){        //按宽度算                CGFloat newWidth = imgWidth/imgHeight*screenHeight;                self.showImageView.frame = CGRectMake((screenWidth-newWidth)/2, 0, newWidth, screenHeight);    }    else {        //按高度算                CGFloat newHeight = imgHeight/imgWidth*screenWidth;        self.showImageView.frame = CGRectMake(0, (screenHeight-newHeight)/2, screenWidth, newHeight);    }</span>

还是下面的方法比较easy, 轻松搞定, 膜拜一下, mark之 !

通过这个函数,我们可以计算一个图片放在另一个 view 按照一定的比例居中显示,可能说的我比较抽象,还是用图来显示,可以说它可以直接一个 image 以任何的比例显示显示在 imageview 中居中所处的位置,拿 UIViewContontAspectFit来演示,

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 300, 300)];imageView.center = self.view.center;imageView.backgroundColor = [UIColor redColor];imageView.contentMode = UIViewContentModeScaleAspectFit;UIImage *image = [UIImage imageNamed:@"mm.jpg"];imageView.image = image; CGRect iamgeAspectRect = AVMakeRectWithAspectRatioInsideRect(image.size, imageView.bounds);NSLog(@"iamgeAspectRect = %@, imageView =%@",NSStringFromCGRect(iamgeAspectRect),NSStringFromCGRect(imageView.frame));[self.view addSubview:imageView];

图片显示如下:(ps:这妹子是我公司一个管理 公司weibo账号 的妹纸,目前我在勾搭,你们不要羡慕,生活依然很美好的嘛!)

呵呵
呵呵

log 打因结果如下:
iamgeAspectRect = {{37.563884156729145, 0}, {224.87223168654171, 300}}, imageView ={{37.5, 183.5}, {300, 300}}

可以从 log 得出 对应的 image 以 aspectFit 的方式在 imageView 的位置,在 imageView 中的位置是(37.5,0)。这样你根本不需要任何多的代码来计算了。(ps:这个函数是在 AV框架的,童鞋们自行导入。)

具体它的其他的好处,如果你是做相机或者图片处理的你就知道它的好处了,什么处理横屏照片了,16:9,1:1,4:3图片在控件中的位置,控件上的点对应图片上的点的位置拉,等等。


0 0
原创粉丝点击