iOS修改截取图片不规范问题

 1 +(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
 2     UIImage *newImage = nil;
 3     CGSize imageSize = sourceImage.size;
 4     CGFloat width = imageSize.width;
 5     CGFloat height = imageSize.height;
 6     CGFloat targetWidth = defineWidth;
 7     CGFloat targetHeight = height / (width / targetWidth);
 8     CGSize size = CGSizeMake(targetWidth, targetHeight);
 9     CGFloat scaleFactor = 0.0;
10     CGFloat scaledWidth = targetWidth;
11     CGFloat scaledHeight = targetHeight;
12     CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
13     if(CGSizeEqualToSize(imageSize, size) == NO){
14         CGFloat widthFactor = targetWidth / width;
15         CGFloat heightFactor = targetHeight / height;
16         if(widthFactor > heightFactor){
17             scaleFactor = widthFactor;
18         }
19         else{
20             scaleFactor = heightFactor;
21         }
22         scaledWidth = width * scaleFactor;
23         scaledHeight = height * scaleFactor;
24         if(widthFactor > heightFactor){
25             thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
26         }else if(widthFactor < heightFactor){
27             thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
28         }
29     }
30     UIGraphicsBeginImageContext(size);
31     CGRect thumbnailRect = CGRectZero;
32     thumbnailRect.origin = thumbnailPoint;
33     thumbnailRect.size.width = scaledWidth;
34     thumbnailRect.size.height = scaledHeight;
35     
36     [sourceImage drawInRect:thumbnailRect];
37     
38     newImage = UIGraphicsGetImageFromCurrentImageContext();
39     if(newImage == nil){
40         NSLog(@"scale image fail");
41     }
42     
43     UIGraphicsEndImageContext();
44     return newImage;
45 }

 

posted @ 2016-01-08 11:01  御剑青冥  阅读(246)  评论(0)    收藏  举报