IOS开发基础之——图像压缩成指定大小(高度/宽度)
2013-10-21 09:30
651 查看
IOS开发基础之——图像压缩成指定大小(高度/宽度)
转自:http://blog.163.com/gaohaijun/blog/static/176698271201192325646792/.h文件:
@interface UIImage (UIImageExt)
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize;
@end
.m文件:
#import "UIImageExt.h"
@implementation UIImage (UIImageExt)
- (UIImage*)imageByScalingAndCroppingForSize:(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; // scale to fit height
else
scaleFactor = heightFactor; // scale to fit width
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;
}
}
UIGraphicsBeginImageContext(targetSize); // this will crop
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width= scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil)
NSLog(@"could not scale image");
//pop the context to get back to the default
UIGraphicsEndImageContext();
return newImage;
}
@end
相关文章推荐
- IOS开发基础之——图像压缩成指定大小(高度/宽度)
- IOS开发基础之——图像压缩成指定大小(高度/宽度)
- IOS开发基础之——图像压缩成指定大小(高度/宽度)
- 每日分享 - 图像压缩成指定大小(高度/宽度)
- 图像压缩成指定大小(高度/宽度)
- android开发游记:图像文件压缩方法总结(将图像压缩到指定大小)
- iOS开发之image图片压缩及压缩成指定大小的两种方法
- iOS开发-基础:获取指定路径文件大小
- iOS开发技巧之:图片压缩成指定的大小
- 一个可以使得上传的图片大小按照指定的宽度,高度自动按比例进行缩放的函数(C#)
- iOS AutoLayout自动布局中级开发教程(4)-label等文字自动适应大小,宽度
- IOS开发中UILabel单行、多行文本计算高度、宽度的技巧
- iOS AutoLayout自动布局中级开发教程(4)-label文字自动适应大小,宽度(新)
- IOS 根据 指定的 字体类型 ,size ,计算 绘制 文本 所需要的 宽度与高度
- iOS开发动态计算cell高度或UILabel多行文本计算高度、宽度的技巧
- 一个关于图片压缩的java类,大小变小,宽度高度不变
- 零基础ios开发(一 改变图片大小和位置)
- iOS 图片按比例压缩,指定大小压缩
- iOS开发 NSString根据字符串一定高度/宽度返回字符串所占的宽度/高度
- 零基础学习IOS开发(三)- cocos2d-x3.0 显示图像及基本动画效果