2013-08-01 132 views
2

我試圖將圖像裁剪成正方形,然後將其縮放到200x200的大小。這是我使用的代碼,但它並不適合我。我得到的圖像有時是不同的方向,或者不是從中心裁剪出來的,或者是比應該更寬的圖像。正確裁剪和縮放UIImage

float scale = _avatar.image.scale; 
UIImageOrientation orientation = _avatar.image.imageOrientation; 

if(_avatar.image.size.width < _avatar.image.size.height){ // avatar is a UIImageView 
    float startingY = (_avatar.image.size.height-_avatar.image.size.width)/2; // image is taller, determine the origin of the width-sized square, which will be the new image 
    CGImageRef imageRef = CGImageCreateWithImageInRect([_avatar.image CGImage], CGRectMake(0, startingY, _avatar.image.size.width, _avatar.image.size.width)); 
    _avatar.image = [UIImage imageWithCGImage:imageRef scale:scale orientation:orientation]; 
    CGImageRelease(imageRef); 
} else { 
    float startingX = (_avatar.image.size.width-_avatar.image.size.height)/2; // image is wider, determine the origin of the height-sized square, which will be the new image 
    CGImageRef imageRef = CGImageCreateWithImageInRect([_avatar.image CGImage], CGRectMake(startingX, 0, _avatar.image.size.height, _avatar.image.size.height)); 
    _avatar.image = [UIImage imageWithCGImage:imageRef scale:scale orientation:orientation]; 
    CGImageRelease(imageRef); 
} 

UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), YES, 0.0); 
[_avatar.image drawInRect:CGRectMake(0, 0, 200, 200)]; 
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

如何實現正確的結果?

+0

有必要嗎?否則,您可以將imageview的大小設置爲200 * 200並將內容模式設置爲aspectfill – Iducool

+0

這就是我需要將其上傳到Web服務器。 – nemesis

回答

5

我建議你使用這個類別的UIImage張貼在github。他們也是非常簡單的類,你也可以使用它們來了解底層的東西。

2

UIImage爲您完成了所有座標和定位技巧。所以你不應該使用UIImage對象的寬度和高度來計算正方形的座標。您可以利用UIKit來裁剪圖像。

CGFloat startingX = 0; 
CGFloat startingY = 0; 
CGFloat squareWidth; 
if(_avatar.image.size.width < _avatar.image.size.height){ // avatar is a UIImageView 
    startingY = (_avatar.image.size.height-_avatar.image.size.width)/2; // image is taller, determine the origin of the width-sized square, which will be the new image 
    squareWidth = _avatar.image.size.width; 
} else { 
    startingX = (_avatar.image.size.width-_avatar.image.size.height)/2; // image is wider, determine the origin of the height-sized square, which will be the new image 
    squareWidth = _avatar.image.size.height; 
} 

UIGraphicsBeginImageContextWithOptions(CGSizeMake(squareWidth, squareWidth), YES, 0.0); 
[_avatar.image drawAtPoint:CGPointMake(-startingX, -startingY)]; // Make an offset to draw part of the image 
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), YES, 0.0); 
[croppedImage drawInRect:CGRectMake(0, 0, 200, 200)]; 
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext();