欢迎来到代码驿站!

iOS代码

当前位置:首页 > 移动开发 > iOS代码

iOS中 UIImage根据屏宽调整size的实例代码

时间:2021-01-25 10:31:46|栏目:iOS代码|点击:

需求:UIImage根据屏幕宽度按照自己本身比例改变高度

上代码,为UIImage创建一个Category

#import "UIImage+UIImageExtras.h" 
@implementation UIImage (UIImageExtras) 
- (UIImage *)imageByScalingToSize:(CGSize)targetSize 
{ 
 UIImage *sourceImage = self; 
 UIImage *newImage = nil; 
 CGSize imageSize = sourceImage.size; 
 CGFloat width = imageSize.width; 
 CGFloat height = imageSize.height; 
 CGFloat targetWidth = targetSize.width; 
 CGFloat targetHeight = targetSize.height; 
 CGFloat scaleFactor = 0.0; 
 CGFloat scaledWidth = targetWidth; 
 CGFloat scaledHeight = targetHeight; 
 CGPoint thumbnailPoint = CGPointMake(0.0,0.0); 
 if (CGSizeEqualToSize(imageSize, targetSize) ==NO) { 
 CGFloat widthFactor = targetWidth / width; 
 CGFloat heightFactor = targetHeight / height; 
 if (widthFactor < heightFactor) 
  scaleFactor = widthFactor; 
 else 
  scaleFactor = heightFactor; 
 scaledWidth = width * scaleFactor; 
 scaledHeight = height * scaleFactor; 
 // center the image 
 if (widthFactor < heightFactor) { 
  
  thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
 } else if (widthFactor > heightFactor) { 
  thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; 
 } 
 } 
 // this is actually the interesting part: 
 UIGraphicsBeginImageContext(targetSize); 
 CGRect thumbnailRect = CGRectZero; 
 thumbnailRect.origin = thumbnailPoint; 
 thumbnailRect.size.width = scaledWidth; 
 thumbnailRect.size.height = scaledHeight; 
 [sourceImage drawInRect:thumbnailRect]; 
 newImage =UIGraphicsGetImageFromCurrentImageContext(); 
 UIGraphicsEndImageContext(); 
 if(newImage == nil) 
 NSLog(@"could not scale image"); 
 return newImage ; 
} 
@end 

在需要使用的地方import然后使用

CGSize size = image.size; 
image = [image imageByScalingToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.width * (size.height / size.width))]; 
self.imageview.image = image; 

上一篇:iOS开发系列--详细介绍数据存取

栏    目:iOS代码

下一篇:iOS 封装导航栏及返回,获取控件所在控制器的实例

本文标题:iOS中 UIImage根据屏宽调整size的实例代码

本文地址:http://www.codeinn.net/misctech/51230.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有