UIImage得一个Category, Resizes(调整尺寸)
在最前边: Category得用法很方便, 举例来说: 新建一个Class文件, 文件名随意需要建立UIImage得Category就按照如下格式添加函数,括号内名称随意, 这种格式, 编译器即认为是一个Category
@interface UIImage (xxx)
@end
@implementation UIImage (xxx)
@end
完整代码如下, 用法见附件Sample Code:
@interface UIImage (Category)
/*
* Resizes and/or rotates an image.
*/
- (UIImage*)transformWidth:(CGFloat)width
height:(CGFloat)height;
@end
@implementation UIImage (Category)
- (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
CategorySampleViewController.m
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"XcodeCrash" ofType:@"png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:imagePath];
UIImage *newImage = [image transformWidth:80.f height:240.f];
UIImageView *imageView = [[UIImageView alloc] initWithImage:newImage];
[newImage release];
[image release];
[self.view addSubview:imageView];
[imageView release];

浙公网安备 33010602011771号