调整图片的尺寸

来源:互联网 发布:淘宝不让卖烟吗 编辑:程序博客网 时间:2024/04/30 02:30

头文件:

 

Ios代码  收藏代码
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface UIImage (Resize)  
  4.   
  5. - (UIImage *)transformWidth:(CGFloat)width height:(CGFloat)height;  
  6.   
  7. @end  

 

实现文件:

 

Ios代码  收藏代码
  1. #import "ImageResize.h"  
  2.   
  3. @implementation UIImage (Resize)  
  4.   
  5. - (UIImage *)transformWidth:(CGFloat)width height:(CGFloat)height {   
  6.     CGFloat destW = width;  
  7.     CGFloat destH = height;  
  8.     CGFloat sourceW = width;  
  9.     CGFloat sourceH = height;  
  10.       
  11.     CGImageRef imageRef = self.CGImage;  
  12.     CGContextRef bitmap = CGBitmapContextCreate(NULL, destW, destH,  
  13.                                                                                             CGImageGetBitsPerComponent(imageRef),   
  14.                                                                                             4 * destW, CGImageGetColorSpace(imageRef),  
  15.                                                                                             (kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst));  
  16.       
  17.     CGContextDrawImage(bitmap, CGRectMake(00, sourceW, sourceH), imageRef);  
  18.       
  19.     CGImageRef ref = CGBitmapContextCreateImage(bitmap);  
  20.     UIImage *result = [UIImage imageWithCGImage:ref];  
  21.     CGContextRelease(bitmap);  
  22.     CGImageRelease(ref);  
  23.       
  24.     return result;  
  25. }  
  26.   
  27. @end  

 

示例:

 

Ios代码  收藏代码
  1. NSString *path = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];  
  2. UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];  
  3. image = [image transformWidth:100.f height:100.f];  
  4. UIImageView *imageView = [[UIImageView alloc] initWithImage:image];  
  5. [image release];  
  6. [self.view addSubview:imageView];  
  7. [imageView release];