现在的位置: 首页 > 综合 > 正文

根据UIImage创建任意大小thumbnail

2013年09月20日 ⁄ 综合 ⁄ 共 1932字 ⁄ 字号 评论关闭

 

来源:苹果开发中文网 www.cocoadev.cn

 

+ (UIImage*)thumbnailOfImage:(UIImage*)image withSize:(CGSize)aSize

{

//NSLog(@"create thumbnail image");

if (!image)

return nil;

CGImageRef imageRef = [image CGImage];

UIImage *thumb = nil;

// struct CGSize imgSize = [imageRef size];

float _width = CGImageGetWidth(imageRef);

float _height = CGImageGetHeight(imageRef);

// hardcode width and height for now, shouldn't stay like that

float _resizeToWidth;

float _resizeToHeight;

_resizeToWidth = aSize.width;

_resizeToHeight = aSize.height;

float _moveX = 0.0f;

float _moveY = 0.0f;

// determine the start position in the window if it doesn't fit the sizes 100%

//NSLog(@" width: %f  to: %f", _width, _resizeToWidth);

//NSLog(@" height: %f  to: %f", _height, _resizeToHeight);

// resize the image if it is bigger than the screen only

if ( (_width > _resizeToWidth) || (_height > _resizeToHeight) )

{

float _amount = 0.0f;

if (_width > _resizeToWidth)

{

_amount = _resizeToWidth / _width;

_width *= _amount;

_height *= _amount;

//NSLog(@"1 width: %f height: %f", _width, _height);

}

if (_height > _resizeToHeight)

{

_amount = _resizeToHeight / _height;

_width *= _amount;

_height *= _amount;

//NSLog(@"2 width: %f height: %f", _width, _height);

}

}

_width = (NSInteger)_width;

_height = (NSInteger)_height;

_resizeToWidth = _width;

_resizeToHeight = _height;

CGContextRef bitmap = CGBitmapContextCreate(

NULL,

_resizeToWidth,

_resizeToHeight,

CGImageGetBitsPerComponent(imageRef),

CGImageGetBitsPerPixel(imageRef)*_resizeToWidth,

CGImageGetColorSpace(imageRef),

CGImageGetBitmapInfo(imageRef)

);

// now center the image

_moveX = (_resizeToWidth - _width) / 2;

_moveY = (_resizeToHeight - _height) / 2;

CGContextSetRGBFillColor(bitmap, 1.f, 1.f, 1.f, 1.0f);

CGContextFillRect( bitmap, CGRectMake(0, 0, _resizeToWidth, _resizeToHeight));

// CGContextRotateCTM( bitmap, 180*(M_PI/180));

CGContextDrawImage( bitmap, CGRectMake(_moveX, _moveY, _width, _height), imageRef );

// create a templete imageref.

CGImageRef ref = CGBitmapContextCreateImage( bitmap );

 

thumb = [UIImage imageWithCGImage:ref];

// release the templete imageref.

CGContextRelease( bitmap );

CGImageRelease( ref );

return [[thumb retain] autorelease];

}

 

抱歉!评论已关闭.