UIImage缩放
前面讲了截取UIImage指定大小区域,很方便的截取`UIImage`。今天要和大家分享的是`UIImage`的缩放。
两种缩放:
1.缩放到指定大小,也就是指定的`size`.
2.等比缩放。
缩放到指定大小
-(UIImage*)imageCompressWithSimple:(UIImage*)imagescaledToSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
[imagedrawInRect:CGRectMake(0,0,size.width,size.height)];
UIImage*newImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnnewImage;
}
等比缩放
通过缩放系数
-(UIImage*)imageCompressWithSimple:(UIImage*)imagescale:(float)scale
{
CGSizesize=image.size;
CGFloatwidth=size.width;
CGFloatheight=size.height;
CGFloatscaledWidth=width*scale;
CGFloatscaledHeight=height*scale;
UIGraphicsBeginImageContext(size);//thiswillcrop
[imagedrawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)];
UIImage*newImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnnewImage;
}
`scale`是缩放系数。
通过计算得到缩放系数
-(UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
UIImage*sourceImage=[UIImageimageNamed:@"test.jpg"];
UIImage*newImage=nil;
CGSizeimageSize=sourceImage.size;
CGFloatwidth=imageSize.width;
CGFloatheight=imageSize.height;
CGFloattargetWidth=targetSize.width;
CGFloattargetHeight=targetSize.height;
CGFloatscaleFactor=0.0;
CGFloatscaledWidth=targetWidth;
CGFloatscaledHeight=targetHeight;
CGPointthumbnailPoint=CGPointMake(0.0,0.0);
if(CGSizeEqualToSize(imageSize,targetSize)==NO)
{
CGFloatwidthFactor=targetWidth/width;
CGFloatheightFactor=targetHeight/height;
if(widthFactor>heightFactor)
scaleFactor=widthFactor;//scaletofitheight
else
scaleFactor=heightFactor;//scaletofitwidth
scaledWidth=width*scaleFactor;
scaledHeight=height*scaleFactor;
//centertheimage
if(widthFactor>heightFactor)
{
thumbnailPoint.y=(targetHeight-scaledHeight)*0.5;
}
elseif(widthFactor<heightFactor)
{
thumbnailPoint.x=(targetWidth-scaledWidth)*0.5;
}
}
UIGraphicsBeginImageContext(targetSize);//thiswillcrop
CGRectthumbnailRect=CGRectZero;
thumbnailRect.origin=thumbnailPoint;
thumbnailRect.size.width=scaledWidth;
thumbnailRect.size.height=scaledHeight;
[sourceImagedrawInRect:thumbnailRect];
newImage=UIGraphicsGetImageFromCurrentImageContext();
if(newImage==nil)
NSLog(@"couldnotscaleimage");
//popthecontexttogetbacktothedefault
UIGraphicsEndImageContext();
returnnewImage;
}