Obj-c代码

iPhone:UIImage 图像截取,…_缩放

 

iPhone:UIImage 图像截取,…_c代码_02

iPhone:UIImage <wbr>图像截取,等比例缩放

1. @interface UIImage(UIImageScale)   
2. -(UIImage*)getSubImage:(CGRect)rect;   
3. -(UIImage*)scaleToSize:(CGSize)size;   
4. @end   
5.    
6. @implementation UIImage(UIImageScale)   
7.    
8. //截取部分图像   
9. -(UIImage*)getSubImage:(CGRect)rect   
10. {   
11.    CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);   
12.    CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));   
13.       
14.    UIGraphicsBeginImageContext(smallBounds.size);   
15.    CGContextRef context = UIGraphicsGetCurrentContext();   
16.    CGContextDrawImage(context, smallBounds, subImageRef);   
17.    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];   
18.    UIGraphicsEndImageContext();   
19.       
20.    return smallImage;   
21. }   
22.    
23. //等比例缩放   
24. -(UIImage*)scaleToSize:(CGSize)size    
25. {   
26.    CGFloat width = CGImageGetWidth(self.CGImage);   
27.    CGFloat height = CGImageGetHeight(self.CGImage);   
28.       
29.    float verticalRadio = size.height*1.0/height;    
30.    float horizontalRadio = size.width*1.0/width;   
31.       
32.    float radio = 1;   
33.    if(verticalRadio>1 && horizontalRadio>1)   
34.    {   
35.        radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;      
36.    }   
37.    else   
38.    {   
39.        radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio;      
40.    }   
41.       
42.    width = width*radio;   
43.    height = height*radio;   
44.       
45.    int xPos = (size.width - width)/2;   
46.    int yPos = (size.height-height)/2;   
47.       
48.    // 创建一个bitmap的context     
49.    // 并把它设置成为当前正在使用的context     
50.    UIGraphicsBeginImageContext(size);     
51.       
52.    // 绘制改变大小的图片     
53.    [self drawInRect:CGRectMake(xPos, yPos, width, height)];     
54.       
55.    // 从当前context中创建一个改变大小后的图片     
56.    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();     
57.       
58.    // 使当前的context出堆栈     
59.    UIGraphicsEndImageContext();     
60.       
61.    // 返回新的改变大小后的图片     
62.    return scaledImage;   
63. }   
64. @end