1.计算图片位置的函数:AVMakeRectWithAspectRatioInsideRect(CGSize aspectRatio, CGRect boundingRect)
通过这个函数,我们可以计算一个图片放在另一个 view 按照一定的比例居中显示,可能说的我比较抽象,还是用图来显示,可以说它可以直接一个 image 以任何的比例显示显示在 imageview 中居中所处的位置(ps:这个函数是在 AV框架的,需要自行导入AVFoundation框架)。
这是一篇介绍比较详细的文章传送门:https://www.jianshu.com/p/827090aa933b
2.一段文字动态行高的计算方法
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSAttributedStringKey, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
使用示例:

3.坐标转换方法
将point由point所在的视图转换到目标视图view中,返回在目标视图view中的point
- (CGPoint)convertPoint:(CGPoint)point toView:(nullable UIView *)view;
将point从view中转换到当前视图,返回在当前视图中的point
- (CGPoint)convertPoint:(CGPoint)point fromView:(nullable UIView *)view;
将rect由rect所在的视图转换到目标视图view中,返回在目标视图view中的rect
- (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;
将rect从view中转换到当前视图,返回在当前视图中的rect
- (CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;
注:toView中的view == nil时,view为[UIApplication sharedApplication].keyWindow;
4. iOS 多张图片合成一张图片,保持原像素不变
- (UIImage *)composeImg {
CGFloat w = self.showImg.size.width;
CGFloat h = self.showImg.size.height;
//以大图大小为底图,为了保证像素是原来像素,一定要用大图(即底图)的size
//以showImg的图大小为画布创建上下文
UIGraphicsBeginImageContext(CGSizeMake(w, h));
[self.imageView.image drawInRect:CGRectMake(0, 0, w, h)];
//计算缩放比例
CGFloat scaleW = self.showImg.size.width/self.imageRect.size.width;
CGFloat scaleH = self.showImg.size.height/self.imageRect.size.height;
if (self.locationLabel) {
CGFloat locLabelW = scaleW * self.locationLabel.width;
CGFloat locLabelH = scaleH * self.locationLabel.height;
[self.locationLabel drawViewHierarchyInRect:CGRectMake(w-locLabelW-10*scaleW,10*scaleH, locLabelW, locLabelH) afterScreenUpdates:YES];
}
//从当前上下文中获得最终图片
UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
//关闭上下文
UIGraphicsEndImageContext();
return resultImg;
}
- (CGRect)imageRect{
return AVMakeRectWithAspectRatioInsideRect(self.showImg.size, self.picBgView.bounds);
}
网友评论