+(UIImage*)imageCompressFitSizeScale:(UIImage*)sourceImage targetSize:(CGSize)size
{
UIImage*newImage =nil;
CGSizeimageSize = sourceImage.size;
CGFloatwidth = imageSize.width;
CGFloatheight = imageSize.height;
CGFloattargetWidth = size.width;
CGFloattargetHeight = size.height;
CGFloatscaleFactor =0.0;
CGFloatscaledWidth = targetWidth;
CGFloatscaledHeight = targetHeight;
CGPointthumbnailPoint =CGPointMake(0.0,0.0);
if(CGSizeEqualToSize(imageSize,size)==NO){
CGFloatwidthFactor = targetWidth / width;
CGFloatheightFactor = targetHeight / height;
if(widthFactor > heightFactor){
scaleFactor = widthFactor;
}
else{
scaleFactor = heightFactor;
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
if(widthFactor > heightFactor){
thumbnailPoint.y=(targetHeight - scaledHeight)*0.5;
}elseif(widthFactor < heightFactor){
thumbnailPoint.x=(targetWidth - scaledWidth)*0.5;
}
}
UIGraphicsBeginImageContext(size);
CGRectthumbnailRect =CGRectZero;
thumbnailRect.origin= thumbnailPoint;
thumbnailRect.size.width= scaledWidth;
thumbnailRect.size.height= scaledHeight;
[sourceImagedrawInRect:thumbnailRect];
newImage =UIGraphicsGetImageFromCurrentImageContext();
if(newImage ==nil){
NSLog(@"scale image fail");
}
UIGraphicsEndImageContext();
returnnewImage;
}
-(UIImage*)scaleToSize:(CGSize)size
{
//创建一个bitmap的context
// 并把它设置成为当前正在使用的context
//Determine whether the screen is retina
if([[UIScreen mainScreen]scale]== 2.0){
UIGraphicsBeginImageContextWithOptions(size,NO,2.0);
}else{
UIGraphicsBeginImageContext(size);
}
// 绘制改变大小的图片
[self drawInRect:CGRectMake(0,0,size.width,size.height)];
// 从当前context中创建一个改变大小后的图片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
//使当前的context出堆栈
UIGraphicsEndImageContext();
// 返回新的改变大小后的图片
return scaledImage;
}
网友评论