UIImage得一个Category, Resizes(调整尺寸)

转自:http://www.cocoachina.com/bbs/read.php?tid-3158.html

写在最前边: 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

任何問題, 歡迎留言討論~阿彌陀佛! 

你可能感兴趣的:(uiimage)