首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

图片比率缩放和裁剪适应区域

2013-01-26 
图片比例缩放和裁剪适应区域@implementation UIImage( resizeAndCropExample )- (UIImage *) resizeToSize

图片比例缩放和裁剪适应区域
@implementation UIImage( resizeAndCropExample )- (UIImage *) resizeToSize:(CGSize) newSize thenCropWithRect:(CGRect) cropRect { CGContextRef context; CGImageRef imageRef; CGSize inputSize; UIImage *outputImage = nil; CGFloat scaleFactor, width; // resize, maintaining aspect ratio: inputSize = self.size; scaleFactor = newSize.height / inputSize.height; width = roundf( inputSize.width * scaleFactor ); if ( width > newSize.width ) { scaleFactor = newSize.width / inputSize.width; newSize.height = roundf( inputSize.height * scaleFactor ); } else { newSize.width = width; } UIGraphicsBeginImageContext( newSize ); context = UIGraphicsGetCurrentContext(); CGContextDrawImage( context, CGRectMake( 0, 0, newSize.width, newSize.height ), self.CGImage ); outputImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); inputSize = newSize; // constrain crop rect to legitimate bounds if ( cropRect.origin.x >= inputSize.width || cropRect.origin.y >= inputSize.height ) return outputImage; if ( cropRect.origin.x + cropRect.size.width >= inputSize.width ) cropRect.size.width = inputSize.width - cropRect.origin.x; if ( cropRect.origin.y + cropRect.size.height >= inputSize.height ) cropRect.size.height = inputSize.height - cropRect.origin.y; // crop if ( ( imageRef = CGImageCreateWithImageInRect( outputImage.CGImage, cropRect ) ) ) { outputImage = [[[UIImage alloc] initWithCGImage: imageRef] autorelease]; CGImageRelease( imageRef ); } return outputImage;}@end

?

热点排行