カテゴリUIImageのトリミング方法の追加


まずUIImageのカテゴリを作成します
//.h 
@interface UIImage(UIImageScale)  
-(UIImage*)getSubImage:(CGRect)rect;  
-(UIImage*)scaleToSize:(CGSize)size;  
@end  
//.m 
@implementation UIImage(UIImageScale)  

//   
-(UIImage*)getSubImage:(CGRect)rect  
{  
    CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);  
    CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));  

    UIGraphicsBeginImageContext(smallBounds.size);  
    CGContextRef context = UIGraphicsGetCurrentContext();  
    CGContextDrawImage(context, smallBounds, subImageRef);  
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];  
    UIGraphicsEndImageContext();  

    return smallImage;  
}  

//   
-(UIImage*)scaleToSize:(CGSize)size   
{  
    CGFloat width = CGImageGetWidth(self.CGImage);  
    CGFloat height = CGImageGetHeight(self.CGImage);  

    float verticalRadio = size.height*1.0/height;   
    float horizontalRadio = size.width*1.0/width;  

    float radio = 1;  
    if(verticalRadio>1 && horizontalRadio>1)  
    {  
        radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;     
    }  
    else  
    {  
        radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio;     
    }  

    width = width*radio;  
    height = height*radio;  

    int xPos = (size.width - width)/2;  
    int yPos = (size.height-height)/2;  

    //  bitmap context    
    //  context    
    UIGraphicsBeginImageContext(size);    

    //      
    [self drawInRect:CGRectMake(xPos, yPos, width, height)];    

    //  context     
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();    

    //  context     
    UIGraphicsEndImageContext();    

    //      
    return scaledImage;  
}  
@end  

メソッドの呼び出し
 UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img21.mtime.cn/mg/2011/09/24/112524.53149978.jpg"]] ]; 
 //   
 image = [image getSubImage:CGRectMake(10, 10, 70, 80)]; 
 //  
 image = [image scaleToSize:CGSizeMake(200, 300)]; 
   NSLog(@"image.size:%@",NSStringFromCGSize(CGSizeMake(imageView.image.size.width, imageView.image.size.height)));   //