iOS UIImage根据屏宽调整size
2017-01-18 10:33
344 查看
需求: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中 UIImage根据屏宽调整size的实例代码
- ios图片缩放,根据UIImageView Frame的尺寸,自动调整UIImage缩放,保证图片显示不变形
- iOS根据网络图片的size大小设置UIImageView的大小
- ios 文字 控件 自适应 高度 宽度 CustomCell 自适应高度+uilabel自动换行+ UITextView 根据内容自动调整高度
- IOS 根据 指定的 字体类型 ,size ,计算 绘制 文本 所需要的 宽度与高度
- iOS UIImageView 大小调整
- 根据viewport的size自动调整fontsize大小
- IOS中测量和调整UIImage到指定CGSize
- iOS常用小功能(获得屏幕图像、压缩图片、加边框、调整label的size)
- iOS 8 Tableview根据AutoLayout自动调整高度,iostableview高度
- iOS 根据字体调整UILabel的大小
- iOS --- 根据字符串的实际大小来计算UILabel的size
- [iOS代码] 根据文字生成图片UIImage
- XCode 6 , IOS 8 中使用 use size classes 的时候 自动调整 自定义table cell的宽度
- 根据size调整图片背景
- iOS版本号,build号获取,根据字符串格式长短动态计算uilabel的size等
- IOS 根据 指定的 字体类型 ,size ,计算 绘制 文本 所需要的 宽度与高度
- ios开发点滴-UILable 根据文字内容进行大小设置 sizeThatFits和sizeToFit
- iOS开发--根据文字动态调整按钮(UIButton)宽度
- iOS 根据字体设置size