头文件:
- #import <Foundation/Foundation.h>
- @interface UIImage (Resize)
- - (UIImage *)transformWidth:(CGFloat)width height:(CGFloat)height;
- @end
实现文件:
- #import "ImageResize.h"
- @implementation UIImage (Resize)
- - (UIImage *)transformWidth:(CGFloat)width height:(CGFloat)height {
- CGFloat destW = width;
- CGFloat destH = height;
- CGFloat sourceW = width;
- CGFloat sourceH = height;
- CGImageRef imageRef = self.CGImage;
- CGContextRef bitmap = CGBitmapContextCreate(NULL, destW, destH,
- CGImageGetBitsPerComponent(imageRef),
- 4 * destW, CGImageGetColorSpace(imageRef),
- (kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst));
- CGContextDrawImage(bitmap, CGRectMake(0, 0, sourceW, sourceH), imageRef);
- CGImageRef ref = CGBitmapContextCreateImage(bitmap);
- UIImage *result = [UIImage imageWithCGImage:ref];
- CGContextRelease(bitmap);
- CGImageRelease(ref);
- return result;
- }
- @end
示例:
- NSString *path = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
- UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];
- image = [image transformWidth:100.f height:100.f];
- UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
- [image release];
- [self.view addSubview:imageView];
- [imageView release];